我有两个HashMap。 mapA.keySet()
是mapB.keySet()
的子集。我想打印每个关键字mapA.get(key) != mapB.get(key)
。但发生在下面的代码中一些奇怪的行为:如果语句后Java HashMap奇怪的行为值发生变化
private static void printMissingNums(int[] a, int[] b) {
Map<Integer, Integer> mapA = intArrToMap(a);
Map<Integer, Integer> mapB = intArrToMap(b);
Set<Integer> missingNums = new TreeSet<Integer>();
for (int key : mapA.keySet()) {
//This version does not work!
if (mapA.get(key) != mapB.get(key)) {
missingNums.add(key);
}
/* This version works (if I comment out the if statement above
and remove the comments around this block of code)
int valA = mapA.get(key);
int valB = mapB.get(key);
if (valA != valB) {
missingNums.add(key);
}
*/
}
// Unrelated to the strange behavior
for (int key : mapB.keySet()) {
if (!mapA.containsKey(key)) {
missingNums.add(key);
}
}
for (int i : missingNums) {
System.out.print(i + " ");
}
}
我得到了奇怪的行为,当我使用的第一个if语句,想知道是怎么回事幕后/为什么它,因为我认为它应该不工作落后。对于我可以访问的特定输入,它会打印3个数字,分别为x,y,z。我检查了HashMaps,发现mapA.get(x) != mapB.get(x)
和mapA.get(y) != mapB.get(y)
,但mapA.get(z) == mapB.get(z)
。
我试着在if语句之前和之后打印值,这些值是相等的,但它以某种方式进入if语句。
注释掉的版本按我期望的那样工作。它只打印出x和y。发生什么事?为什么看起来像HashMap值正在改变,即使我没有改变任何东西?
这是输入:http://pastebin.com/JyYxspjx。第一行是第一个数组中的元素数量,后跟空格分隔的整数。 下一行之后是第二个数组中的元素数量,后跟空格分隔的整数。
为什么8622是唯一具有相同值的密钥,但比较结果是错误的?
可能是因为评论版本比较了原语而其他版本的对象。 – dambros
除了一个特定的键8622以外,怎么比较这些原语是很好的。(我将输入数组添加到原始帖子中)。 8622与其他比较有什么不同? – mkim123