I have an object that contains several fields (ints, Strings, etc) but also a HashMap and an ArrayList. This objects holds parameters used to later build a database query but there are times when I need to re-use all of the exact same parameters for an additional query, except for different items in the ArrayList.
I’ve noticed that when I change what’s in the array list, it always changes the original object. I’ve figured out how to make a shallow copy by overriding the clone() method but the array list always remains shared by any copy of the object. Before diving into deep copies and the like I think I need advice on whether that’s the best route.
Here’s an example of the object I need to find a way to duplicate.
public class QueryParameters implements Cloneable {
protected HashMap<String,String> foundArgs = new HashMap<String,String>();
protected ArrayList<ActionType> action_types = new ArrayList<ActionType>();
protected String lookup_type = "lookup";
protected Location loc;
protected Vector player_location;
protected int id = 0;
protected int radius;
protected boolean allow_no_radius = false;
protected String player;
protected String world;
protected String time;
protected String entity;
protected String block;
// ... lots of getters/setters
}
I could always make a new instance and use getters/setters to transfer the data but that feels too verbose to me – there are about 15 fields I’d have to copy over and if I ever add new ones I’d need to remember to add them here.
What’s the best way for me to obtain a new instance/clone so that changes to action_types doesn’t affect the original object
I suggest writing a clone method that uses super.clone() to copy most of the fields, and then replaces the ArrayList in the clone. Something like this: