我有一个character
类,我想在某个事件之前创建一个副本,这样,如果用户搞砸了,他可以重试该副本。为此,我使用如下的复制构造函数:
public class character
implements Serializable
{
private String name;
private HashMap<String,Integer> values = new HashMap<>();
private ArrayList<String> traits = new ArrayList<>();
private enums.playerRelations playerRelation;
private static character playerCharacter = new character();
private transient Runnable combatAI;
private transient Runnable tradingAI;
private ArrayList<character> companions = new ArrayList<>();
private ArrayList<item> inventory = new ArrayList<>();
private int maximumInventorySize = 20;
private int maximumSkillSlots = 10;
private transient ArrayList<Pair<skill,Boolean>> skills = new ArrayList<>();
private int portraitResource = R.drawable.ic_bear;
private event eventContext;
public character(character o)
{
name = o.name;
values = new HashMap<>(o.values);
traits = new ArrayList<>(o.traits);
playerRelation = o.playerRelation;
combatAI = o.combatAI;
tradingAI = o.tradingAI;
companions = new ArrayList<>(o.companions);
inventory = new ArrayList<>(o.inventory);
maximumInventorySize = o.maximumInventorySize;
maximumSkillSlots = o.maximumSkillSlots;
skills = new ArrayList<>(o.skills);
portraitResource = o.portraitResource;
eventContext = o.eventContext;
}
// ...
}
但是,我不知道如何深度克隆Runnable
对象。我该如何深层复制这些内容?使用复制构造函数完全可以吗?
我注意到Runnable
与character
的其他成员是不同的,因为关注的部分存储在函数而不是属性中...
答案 0 :(得分:1)
如果您仅知道combatAI
是Runnable
,那么您就无法对其进行深度复制-可以说它没有深度-仅{{1} }。
您可能需要重新考虑这种方法,并在游戏(?)中明确拥有检查点,以便可以根据检查点数据创建Runnable
和其余状态。
还请注意,您的combatAI
副本仅一层深,原始inventory
和新character
共享相同的item
。与companions