I have a class character that I'd like to create a copy of before a certain event so that if the user screws up he can retry with the copy. To implement this I use the copy constructor like this:
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;
}
// ...
}
However, I don't know how to deep clone a Runnable object. How can I deep copy those? Is that at all possible using the copy constructor?
I notice that Runnable is different from the other members of character insofar that the part of concern is stored within a function rather than an attribute...
Runnablebut a strategy interface of your own which includes a proper clone method. As a side note, your class looks very overburdened with properties, splitting and/or grouping them would be an improvement.