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

HashMap element is removed when another HashMap name remove an element

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 在内部引用同一个地图。

因此,当您从一个元素中删除元素时,更改也会反映在另一个元素中。由于底层都指向同一个对象

如果你想让 randomPersonList 分开,你可以做的是:

HashMap<Integer, String> randomPersonList= new HashMap<>(appearList);

这将使用 appearList

中的数据创建一个新的 HashMap

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