I have a hashmap which I want to copy for other use. But whenever I copy it and reuse it, it also changes the original one.
Why is that?
do {
Map<Integer, Map<String, Object>> map1 = originalMap;
//at the second iteration originalMap is the same as map1 of the last iteration,
//eventhough the change was nog accepted;
//do something with map1 (change value);
if(change is accepted) {
originalMap = map1;
}
} while(iteration < 10);
Thanks in advance
public static <Integer,String, Schedule>Map<Integer, Map<String, Schedule>> deepCopy(Map<Integer, Map<String, Schedule>> original) {
Map<Integer, Map<String, Schedule>> copy = new HashMap<Integer, Map<String, Schedule>>();
for (Map.Entry<Integer, Map<String, Schedule>> entry : original.entrySet()) {
copy.put(entry.getKey(), deepCopy2(entry.getValue()));
}
return copy;
}
public static <String, Schedule>Map<String, Schedule> deepCopy2(Map<String, Schedule> original) {
Map<String, Schedule> copy = new HashMap<String, Schedule>();
for (Map.Entry<String, Schedule> entry : original.entrySet()) {
copy.put(entry.getKey(), entry.getValue());
}
return copy;
}
What you did was not to create a copy of the map, but of the reference to it. when two references point to the same object, changes to one will reflect in the other.
Solution 1: If this was a Map from some simple type to another, you would do this instead:
This is called a Copy Constructor. Almost All standard Collection and Map implementations have one, and it’s usually the simplest way to clone a simple structure.
This will work fine as long as
SomeTypeandOtherTypeare immutable (e.g.Integerand otherNumbertypes,Boolean,String, but not Collections, Dates, Maps, Arrays etc.)If not, as other answerers and commenters have pointed out, you also need to copy the map values.
Solution 2: Here’s a quick and dirty version that should be safe:
But actually, I like Hunter’s idea of providing a deep copy method. So here’s Solution 3:
my own version using generic parameters:
You can call it like this:
Update
I’ve hacked together a class that performs deep cloning for Maps, Collections and Arrays (primitive and otherwise). Usage:
Here it is: