Search code examples
javaintegercomparison

Integer comparisons in Java


Recently in one programming contest (where I used java8 although I could have used any other language), I encountered this issue. Please help me understand the issue.

I had to write this statement at one point. All visible testcases passed. But when I submitted the code, I could see 6/15 test cases failed.

// list1 and list2 are ArrayList<Integer> type
if(list1.get(i) == list2.get(i){
...
...
}

I don't know what I was thinking, but I changed the above code into something like this.

if(Integer.compare(list1.get(i), list2.get(i))==0){
...
...
}

Now, all the test cases passed. Can someone help me understand why test cases were failing in the first code?

0<=list1[i], list2[i]<=10^9


Solution

  • Any successful comparison was happenstance due to certain caching of Integer values or luckily comparing the same object references. But lists contain objects. In this case the Integer wrapper class. So do one of the following to test for equality.

    if (list1.get(i).compareTo(list2.get(i)) == 0) {
    ...
    }
    

    or

    if (list.get(i).equals(list2.get(i))) {
       ...
    }
    

    Never test objects for equality using ==. Always use equals(). For doing inequality tests such as < and > use compareTo which is defined in the Comparable interface Java doc.