Reputation: 631
I have some code which creates an ArrayList of HashMaps, I then need a copy of that ArrayList of HashMaps for performing calculations, but I want the original to stay the same.
I have tried all sorts, from people's SO answers, here's my current code:
List<Map> counts = new ArrayList<>();
The counts
list is filled with HashMaps.
I need a copy of that but I don't want the calculations I perform on the copy to affect the original.
I have tried:
List<Map> copyCounts = new ArrayList<Map>(counts);
But whenever I perform changes it alters the original
Upvotes: 0
Views: 530
Reputation: 11474
Here is how to create a deep copy:
List<Map> counts = ...
List<Map> copy = new ArrayList<>();
for(Map m : counts){
copy.add(new HashMap(m));
}
Upvotes: 2
Reputation: 2495
That's because all the maps you're adding to your new array list are still by reference. You also need to copy the individual maps as well.
Upvotes: 1