更新HashSet类型<integer> </integer>的HashMap值

时间:2013-11-18 01:26:45

标签: 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]

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

2 个答案:

答案 0 :(得分:3)

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

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

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

正确的方法是

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

这样,每个密钥都有自己的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++);

答案 1 :(得分:1)

首先,当你执行if (hashMap1.containsKey(key))时,java循环检查每个键以检查密钥是否存在,这样你就不需要编写for循环代码靠自己。

然后,您不需要编写hashMap1.remove(key),因为当向Java映射插入存在的键时,映射将找到现有的(键,值)对并覆盖新的(键,值)对。

以下是Set<Integer> valuesCopy;之后修改后的代码:

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.put(key, valuesCopy); // insert the key-value pairs
}

只需删除for (String key : mapKeys)hashMap1.remove(key)代码段,然后您就可以获得所需的结果。

相关问题