我目前有两个班级,宇宙和世界。 Universe类具有ArrayList字段,该字段列出了该Universe的所有世界。我希望能够复制一个宇宙,然后在其中添加一个世界,这样我就有两个宇宙对象,一个对象的世界比另一个少。
这是Universe类:
public class Universe {
private ArrayList<World> worlds;
private int worldCount;
private boolean reflex;
private boolean trans;
private boolean symm;
private boolean hereditary;
public Universe(ArrayList<World> worlds, int worldCount, boolean reflex, boolean trans, boolean symm, boolean hereditary) {
this.worlds = worlds;
this.worldCount = worldCount;
this.trans = trans;
this.reflex = reflex;
this.symm = symm;
this.hereditary = hereditary;
if (this.symm && this.trans) { // symmetry and transitivty makes reflexivity
this.reflex = true;
}
}
public Universe(Universe u) { // creates a shallow copy of the other universe
this(u.getWorlds(), u.getWorldCount(), u.getReflex(), u.getTrans(), u.getSymm(), u.getHereditary());
}
@Override
public Object clone() {
Universe u = null;
try {
u = (Universe) super.clone();
}catch(CloneNotSupportedException e) {
u = new Universe(this.getWorlds(), this.getWorldCount(), this.getReflex(), this.getTrans(), this.getSymm(), this.getHereditary());
}
return u;
}
}
世界级:
public class World {
private Universe parentUniverse;
private String worldName;
private ArrayList<Relation> relations;
private ArrayList<ExprStr> expressions;
public World(Universe u) {
this.parentUniverse = u;
int count = u.getWorldCount();
String countStr = Integer.toString(count);
this.worldName = "";
this.worldName += 'w' + countStr;
this.relations = new ArrayList<Relation>();
if (this.parentUniverse.getReflex()) {
this.addRelation(this, true, true);
}
this.expressions = new ArrayList<ExprStr>();
}
}
World类在其自己的Universe中为其自身命名,并且toString方法返回该名称。 Universe的toString方法返回所有世界的列表。
我有代码:
Universe y = new Universe();
World d = new World(y);
y.addWorld(d);
Universe x = (Universe) y.clone(); // have to type cast to use clone()
World d1 = new World(x);
x.addWorld(d1);
System.out.println(y);
System.out.println(x);
但是输出是:
[w0, w1]
[w0, w1]
即使,如果正确地进行深度复制,我也希望一个宇宙比另一个世界拥有更多的世界。
我也需要深深复制世界一流吗?我究竟做错了什么?
谢谢! :)