我有兩個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