【问题标题】:HashMap element is removed when another HashMap name remove an element当另一个 HashMap 名称删除一个元素时,HashMap 元素被删除
【发布时间】:2021-11-19 07:52:39
【问题描述】:

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);
    }
}

【问题讨论】:

    标签: java hashmap


    【解决方案1】:
    HashMap<Integer, String> randomPersonList = appearList;
    

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

    【讨论】:

      【解决方案2】:

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

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

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

      HashMap randomPersonList= new HashMap(appearList);

      这将使用来自出现列表的数据创建一个新的 HashMap

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2020-02-28
          • 2022-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多