[英]HashMap element is removed when another HashMap name remove an element
出现列表是具有固定数据的appearList
。 我愿意:
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 成为与出现列表相同的 object 的引用。 因此,使用这两个变量,您将访问相同的 object。 创建两个 HashMap 或创建一个clone
。
randomPersonList 和 appendList 在内部引用相同的 Map。
因此,当您从一个元素中删除元素时,变化也会反映在另一个元素中。 由于底层两者都指向相同的 object
如果您希望 randomPersonList 分开,您可以做的是:
HashMap<Integer, String> randomPersonList= new HashMap<>(appearList);
这将使用来自出现列表的数据创建一个新的 HashMap
您正在做浅拷贝,这意味着randomPersonList
和appearList
都指向相同的引用。 您需要使用putAll()
方法或迭代执行深拷贝,以确保两个 hash 映射是不同的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.