1

I'm using a HashMap that I duplicate, but when I change values from the second HashMap, the first HahsMap get its values also change.

There is my code :

HashMap<String, processing.core.PImage> firstMap = new HashMap<>();
// Filling the first HashMap with values.
System.out.println(firstMap.get("test").height); // returning 16

// Then, I duplicate the HashMap :
HashMap<String, processing.core.PImage> secondMap = new HashMap<>(firstMap);

secondMap.forEach((name, image) -> {
  image.resize(1, 1); 
  // This sets height and width of images as 1
  // BUT, logically, it must change only values from SECONDMap, not FIRSTMap
});

System.out.println(firstMap.get("test").height); // returning 1
// It returns 1 but I didn't change the values from the FIRST map ??

So I just don't understand what is happening and how to fix it ?

Ayfri
  • 570
  • 1
  • 4
  • 24
  • 1
    Copying the map doesn't copy the things stored in the map: you just put the same instances into a different map instance. In other words: you've taken a *shallow* copy. – Andy Turner Apr 25 '20 at 19:01
  • you looking to deep copy instead of shallow copy – Nikolan Asad Apr 25 '20 at 19:08
  • If I might ask - what kind of code are you writing? Is this a Java program that uses Processing as "just another library"? Because if so, this is _not_ a Processing question but just a normal question about deep copying Java datastructures. – Mike 'Pomax' Kamermans Apr 25 '20 at 20:59

1 Answers1

1

What you did is called Shallow Copy, which is making a new Hash Map that points to the keys and values of the first Hash Map, that's why when one is changed the other feels the change.

What you need to do is a Deep Copy, which can be done by iterating over the first Hash Map, and coping all the data one by one.

HashMap<String, processing.core.PImage> secondMap = new HashMap<String, processing.core.PImage>();
for (Map.Entry<String, processing.core.PImage> entry : firstMap.entrySet())
{
    secondMap.put(entry.getKey(), entry.getValue());
}
Ahmed Hammad
  • 2,798
  • 4
  • 18
  • 35