user3667111
user3667111

Reputation: 631

Creating a copy of an ArrayList of HashMaps

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

Answers (2)

satnam
satnam

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

Charles Durham
Charles Durham

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

Related Questions