0

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

user3667111
  • 611
  • 6
  • 21

2 Answers2

2

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));
}
satnam
  • 10,719
  • 5
  • 32
  • 42
1

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.

Charles Durham
  • 2,445
  • 16
  • 17