复制HashMap,但更改为2 [duplicate]

问题描述 投票:0回答:1

我使用的是我复制的HashMap,但是当我从第二个HashMap更改值时,第一个HahsMap的值也会更改。

有我的代码:

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 ??

所以我只是不了解发生了什么以及如何解决?

java hashmap processing
1个回答
0
投票

您所做的称为,它正在制作一个新的Hash Map,该哈希图指向第一个Hash Map的键和值,这就是为什么当一个更改时,另一个感觉到更改的原因。

© www.soinside.com 2019 - 2024. All rights reserved.