我在更新 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/