-2

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

kakashiOfSharingan
  • 121
  • 1
  • 1
  • 7
  • 2
    "*`list1.get(i) == list2.get(i)==0`*" - [This does not compile](https://ideone.com/GUDVWR). – Turing85 Nov 01 '21 at 14:58
  • `Integer` is an object. So unlike `int` you cannot compare them with just `==` and should use `equals`. The fact that comparing Integers with `==` works for a specific range (-127 to 128 afaik) is because the objects for values are internally cached and reused. See https://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127 – OH GOD SPIDERS Nov 01 '21 at 15:01
  • "Integer.compare(list1.get(i), list2.get(i))==0" edited. @Turing85 – kakashiOfSharingan Nov 01 '21 at 17:06
  • I would suggest to use `Objects.equals(list1.get(i), list2.get(i))`. This is semantically equal to `Integer.compare(list1.get(i), list2.get(i))==0`, but a) is easier to read and understand and b) avoids unnecessary unboxings. – Turing85 Nov 01 '21 at 17:09

1 Answers1

1

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.

WJS
  • 36,363
  • 4
  • 24
  • 39