A.get(i)==A.get(j) does not work but A.get(i)-A.get(j)==0 works?

test case
3 5000 5000 5000

You are getting Integer objects from the list not primitives (int). Even if values are the same, objects might be different.

== only compares the memory addresses and not the actual values. A.get(i).equals(A.get(j)) is the correct way of comparing non null objects but difference will also work in this particular case.

1 Like

As @cristizmf mentioned, you are getting Integer objects from the list, not the primitives (int).
So a better way if you need to use the logical operators for comparison is to use: A.get(i).intValue()==A.get(j).intValue() .

Doesn’t auto unboxing automatically convert the Integer object to primitive int value?

There is no unboxing involved because objects are compared as returned from the list without any conversion to primitive int type.

refer to this magic of java

Click here to start solving coding interview questions