我正在用java进行一些模拟。我试图提前几步模拟树的一个节点,然后丢弃所有更改并返回原始状态。但是 clone() 并没有返回正确的结果。
节点类:
public class TreeNode implements Serializable,Cloneable{
HashMap<Integer, Tracker> trackers;
public Object clone(){
try{
TreeNode node = (TreeNode) super.clone();
HashMap<Integer, Tracker> newTrackers = new HashMap<Integer, Tracker>;
for (int i=0:i<4:i++){
newTrackers.put(i, node.trackers.get(i).clone());
}
node.trackers = newTrackers;
return node;
}catch(CloneNotSupportException e){
}
return null;
}
public run(){
TreeNode current = root;
TreeNode CopyNode = (TreeNode) current.clone();
foo(CopyNode);
//Here both current and CopyNode have the same changes at trackers
//made by foo()
}
}
跟踪器类:
public class Tracker implements Serializable,Cloneable{
private final Player player;
public Tracker clone(){
try{
Tracker newTracker = (Tracker) super.clone();
newTracker.player = player.clone();
return newTracker;
} catch (CloneNotSupportException e){
}
return null;
}
玩家等级:
public class Player implements Serializable,Cloneable{
private int points;
public Player clone(){
try{
return (Player) super.clone();
}catch (CloneNotSupportException e){
}
return null;
}
}
注意:我不能为此使用 apache 函数,例如 org.apache.commons.lang.SerializationUtils