看看这节课。我从一本很棒的书"On Java“中获得了下面的课程,但是我如何才能深入地复制这个类呢?
public class Snake implements Cloneable {
private Snake next;
private char c;
public Snake(int i, char x) {
c = x;
if(--i > 0)
next = new Snake(i, (char)(x + 1));
}
public void increment() {
c++;
if(next != null)
next.increment();
}
@Override public String toString() {
String s = ":" + c;
if(next != null)
s += next.toString();
return s;
}
@Override public Snake clone() {
try {
Snake snake = (Snake) super.clone();
return snake;
} catch(CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Snake s = new Snake(5, 'a');
System.out.println("s = " + s);
Snake s2 = s.clone();
System.out.println("s2 = " + s2);
s.increment();
System.out.println(
"after s.increment, s = " + s);
System.out.println(
"after s.increment, s2 = " + s2);
}
}
发布于 2022-02-17 22:36:20
解决方案1
@Override
public Snake clone() {
return new Snake(getLevel(), c);
}
private int getLevel() {
int i = 1;
Snake current = this;
while (current.next != null) {
i++;
current = current.next;
}
return i;
}
解决方案2
创建构造函数
private Snake(char c, Snake ob) {
this.c = c;
if (ob.next != null) {
this.next = new Snake(ob.next.c, ob.next);
}
}
克隆方法:
@Override
public Snake clone() {
return new Snake(c, this);
}
解决方案3
@Override
public Snake clone() {
Snake deepCopy;
try {
deepCopy = (Snake) super.clone();
Snake current = this;
Snake deepCopyNext = deepCopy;
while (current.next != null) {
deepCopyNext.next = new Snake(0, current.next.c);
deepCopyNext = deepCopyNext.next;
current = current.next;
}
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
return deepCopy;
}
解决方案4 (阿帕奇公域 Lang)
类必须实现java.io.Serializable
public class Snake implements Cloneable, Serializable
克隆方法:
@Override
public Snake clone() {
return org.apache.commons.lang3.SerializationUtils.clone(this);
}
解决方案5(用葛森序列化JSON)
@Override
public Snake clone() {
com.google.gson.Gson gson = new com.google.gson.Gson();
return gson.fromJson(gson.toJson(this), Snake.class);
}
https://stackoverflow.com/questions/71161311
复制相似问题