I have two HashMaps. mapA.keySet() is a subset of mapB.keySet(). I want to print every key for which mapA.get(key) != mapB.get(key). But some strange behavior occurs in the code below:
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 + " ");
}
}
I get strange behavior when I use the first if statement and want to know what is going on behind the scenes / why it's not working as I think it should. For a specific input that I have access to, it prints 3 numbers called x, y, z. I check the HashMaps and find that mapA.get(x) != mapB.get(x) and mapA.get(y) != mapB.get(y) but mapA.get(z) == mapB.get(z).
I tried printing the values before and after the if statement and the values are equal but it somehow goes into the if statement.
The commented out version works as I expect. It prints out only x and y. What is happening? Why does it seem like the HashMap values are changing even though I am not changing anything?
Here is the input: http://pastebin.com/JyYxspjx. The first line is the number of elements in the first array, followed by space separated integers. the next line after those is the number of elements in the second array, followed by space separated integers.
How come 8622 is the only key that has the same value but the comparison is false?