java - 更新 HashSet<Integer> 类型的 HashMap 值

标签 java hashmap

我在更新 Set 类型的 HashMap 值时遇到问题。用键值对初始化HashMap后,我想向现有值Set插入一个新值,并且每次插入都会递增新值。我的代码如下:

    public static void main(String[] args)
    {
        String[] mapKeys = new String[]{"hello", "world", "america"};
        Map<String, Set<Integer>> hashMap1 = new HashMap<String, Set<Integer>>();
        Set<Integer> values = new HashSet<Integer>();

        for (int i = 0; i < 10; i++)  // initialize the values to a set of integers[1 through 9]
        {
            values.add(i);
        }

        for (String key : mapKeys)
        {
            hashMap1.put(key, values);
        }

        StdOut.println("hashMap1 is: " + hashMap1.toString());

        int newValues = 100; // insert this newValues (incremented at each insert) to each value
        Set<Integer> valuesCopy;

        for (String key : mapKeys)
        {
            if (hashMap1.containsKey(key))
            {
                valuesCopy = hashMap1.get(key); // first, copy out the existing values

                valuesCopy.add(newValues++); // insert the newValues to the value Set
                hashMap1.remove(key);// remove the existing entries
                hashMap1.put(key, valuesCopy); // insert the key-value pairs

            }
        }

        StdOut.println("the updated hashMap1 is: " + hashMap1.toString());


    }

执行代码时,每个 HashMap 键都与同一组整数相关联: [102, 0, 1, 2, 100, 3, 101, 4, 5, 6, 7, 8, 9],但是,我真正想要的是在每一组中只插入一个数字,这就是我想要的:[ 0, 1, 2, 100, 3, 4, 5, 6, 7, 8, 9]

我需要帮助理解这一点:为什么所有新插入的值都是相同的?如何让它按我的意愿工作?感谢您的帮助

最佳答案

原因是Java中的每个对象符号都是对实际对象的引用。在这一部分

for (String key : mapKeys)
{
    hashMap1.put(key, values);
}

您将每个键与对相同Set<Integer>的引用关联起来。 ,因此当您更改其中之一时,所有这些都会更改。

正确的做法是

for (String key : mapKeys)
{
    hashMap1.put(key, new HashSet<Integer>(values));
}

这样每个 key 都会有自己的 Set 副本用 values 的内容初始化.

有了这个事实,你也可以看到这里的代码

            valuesCopy = hashMap1.get(key); // first, copy out the existing values

            valuesCopy.add(newValues++); // insert the newValues to the value Set
            hashMap1.remove(key);// remove the existing entries
            hashMap1.put(key, valuesCopy); // insert the key-value pairs

很冗长并且会带来不必要的开销。只需使用

hashMap1.get(key).add(newValues++);

关于java - 更新 HashSet<Integer> 类型的 HashMap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038579/

相关文章:

java - context.remove(this) 引起的 RunTimeException

java - 在 Java 调试器接口(interface) (JDI) 中调用静态方法

java - Play 框架离线分发下载存储库

ruby - 如何从哈希中获取下一个哈希元素?

java - 如何删除java hashmap中特定对象的所有映射?

java - 两个线程访问同一个变量锁应用程序

java - XMLHttpRequest 状态为 0

java - 为什么迭代器不抛出并发修改异常?

java - 根据值对 Map 内的 HashMap 进行排序

java - HashMap 键/值引用