当另一个HashMap名称移除一个元素时,会移除HashMap元素



appearList是一个具有固定数据的HashMap。我知道:

randomPersonList = appearList;

然后,当我从randomPersonList中移除一个元素时,appearList上的那个元素也会意外地被移除。我希望appearList保持原样。

有人能告诉我为什么以及如何更正我的代码吗?

package personaltries;
import java.util.*;
public class issue {
public static void main(String[] args) {
HashMap<Integer, String> appearList = new HashMap<>();
appearList.put(1,"a");
appearList.put(2,"b");
HashMap<Integer, String> randomPersonList = appearList;
Scanner scanner = new Scanner(System.in);
boolean keepPlaying = true;
while (keepPlaying) {
System.out.println("1. Pick randomly a person");
int chosenOption = scanner.nextInt();
if (chosenOption == 1) {
pickRandomlyAPerson(randomPersonList, appearList);
} else {
System.out.println("Wrong option");
}
}
}
private static String pickRandomlyAPerson(HashMap<Integer, String> randomPersonList, HashMap<Integer, String> appearList) {
if(randomPersonList.size()==0){
randomPersonList=appearList;
}
List<Integer> listKey = new ArrayList<>(randomPersonList.keySet());
int randomIndex = new Random().nextInt(listKey.size());
int randomNumber = listKey.get(randomIndex);
String name  = randomPersonList.get(randomNumber);
randomPersonList.remove(randomNumber);
System.out.println(name+" please!");
System.out.println(randomPersonList);
return (name);
}
}
HashMap<Integer, String> randomPersonList = appearList;

使randomPersonList成为对与appearList相同对象的引用。因此,对于这两个变量,您访问的是同一个对象。创建两个HashMap或创建一个clone

randomPersonList和appearList在内部引用同一Map。

所以,当您从一个元素中移除元素时,变化也会反映在另一个元素上。由于底层两者都指向同一对象

如果你想让randomPersonList独立,你可以做的是:

哈希映射<整数,字符串>randomPersonList=新的HashMap<gt;(appearList(;

这将使用appearList 中的数据创建一个新的HashMap

您正在执行浅层复制,这意味着randomPersonListappearList都指向同一引用。您需要使用putAll()方法或迭代来执行深度复制,以确保两个哈希映射都是不同的引用。

最新更新