-2

I have a use case which looks something like this :

    Map<String,String> pr = new HashMap<>();
    pr.put("ab","ab");
    pr.put("xy","xy");
    Map<String,String> prNew = new HashMap<>();
    prNew = pr;
    prNew.remove("ab");
    System.out.println(pr);
    System.out.println(prNew);

This is the output i got :

{xy=xy}
{xy=xy}

But I was expecting 'pr' to remain as :

{ab=ab, xy=xy}

It looks like prNew took a reference of pr, and any modifications to prNew will modify pr as well.

So how do i get around this? In my use case I need to take a copy of pr and make some changes but it should not affect the original pr.

Any help would be greatly appreciated. Thanks.

CodePlorer
  • 153
  • 1
  • 15
  • You want to copy your map, not just assign it. HashMap already has a copy constructor that you can use: `prNew = new HashMap<>(pr);` – OH GOD SPIDERS Mar 27 '18 at 12:04
  • It's not "it looks like" ==> it is ! – azro Mar 27 '18 at 12:05
  • Read this for reference: [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). Also: [Copying a HashMap in Java](https://stackoverflow.com/questions/10079266/copying-a-hashmap-in-java) – Malte Hartwig Mar 27 '18 at 12:07

2 Answers2

2

Why the code doesn't work

You create the following in memory:

enter image description here

So when you change 1 map, you change both, because they are the same map.

Solution

You need to make a copy of the map if you want to change 1 while keeping the other the same.

You can do this using the constructor which takes a map in.

jrtapsell
  • 6,719
  • 1
  • 26
  • 49
1
  • for the moment pr and prNew reference the same object, a modification on pr or prNew is the same, they are just aliases for the same Map

  • when you create prNew you have to use the constructor that takes another Map, to make a copy of, all the mappings will be copied into the new one

//...

Map<String, String> prNew = new HashMap<>(pr); // <--
prNew.remove("ab");
System.out.println(pr);     // {ab=ab, xy=xy}
System.out.println(prNew);  // {xy=xy}
azro
  • 53,056
  • 7
  • 34
  • 70