Search code examples
javahashmapequality

Java Map Value Equality


While writing a graph algorithm, I saw that this -

Definition:

Map<Integer, Integer> componentNames = new HashMap<Integer, Integer>();

CASE I:

if (componentNames.get(A) == componentNames.get(B)) {
    System.out.printn("Hi");
}

Does not print anything.

CASE II:

int componentNameA = componentNames.get(A);
int componentNameB = componentNames.get(B);
if (componentNameA == componentNameB) {
    System.out.printn("Hi");
}

Prints "Hi"

I have printed to check the values. And, they were indeed same. This is the first time I have seen strange behavior for Java. What could be the reason for this?


Solution

  • CASE I:

    if (componentNames.get(A) == componentNames.get(B)) {
        System.out.printn("Hi");
    }
    

    The code doesn't enter the if condition because you are trying to compare two Integer references using == which will only return true if the LHS and RHS refer to the same object. In your case, it is safe to assume that componentNames.get(A) and componentNames.get(B) both return a reference to a separate Integer object.

    It would be helpful to know that the JVM caches the values for wrapper classes and it is quite possible that the above if condition may be true if the JVM has cached the int value returned by componentNames.get(A) and componentNames.get(B). The JVM used to cache Integer values ranging between -128 to 127 but modern JVMs can cache values greater than this range as well.

    int componentNameA = componentNames.get(A);
    int componentNameB = componentNames.get(B);
    if (componentNameA == componentNameB) {
        System.out.printn("Hi");
    }
    

    The code enters condition because you are unboxing an Integer into an int and the comparison is done between two primitive values.

    In general, two references when compared using == will only return true if both the references point to the same object. Therefore, it is advisable to compare two references using equals if you are checking for equality and compare them using == if you are looking to check for identity.