4
List<Integer> test = List.of(955, 955);
if (test.get(1) == test.get(0))
...

Above condition results in false

List<Integer> test = List.of(955, 955);
int a = test.get(1);
int b = test.get(0);
if (a == b)
...

The above condition returns true.

Why is that the case? What is the difference between the snippets?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 4
    The difference is auto-unboxing. In the first comparison you compare two `Integer` objects using `==` which will only be true when they are *the same object* (i.e. if they are distinct object with identical values they won't compare equal). In the second case you unbox them both into `int` values, where `==` compares the actual value (since that's the only thing an `int` has). – Joachim Sauer Jun 02 '21 at 20:03
  • 1
    `test.get(1)==test.get(0)` compares reference-equality (since `test.get(...)` returns an `Integer`), while `int a=test.get(1); int b=test.get(0); if(a==b) { ... }` autoboxes the `Integer`s into `int`s and then compares value-equality. – Turing85 Jun 02 '21 at 20:04

3 Answers3

9

In one case, you're comparing two Integer object references. In the other case, you're comparing two ints. When using the == operator to compare object references, it will return False if they are not the same object, even if they do wrap the same value.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • I'm just trying to understand why the Java implementation doesn't override the == operator for Integer objects, this seems like the obvious thing to do. They could always just provide a method for comparing instances if they really needed it... – ibrust Apr 16 '23 at 22:27
1

First Code Snippet: You are comparing the object reference, meaning the specific object reference that the object is pointing too. In this case you are comparing an Integer which is a wrapper class for int.

Second Code Snippet: You are comparing the an 'int' to another 'int'.

Example:

Think about it this way: if two people had the name John, in the first scenario we are comparing the people named John, whereas in the second scenario we are comparing the name John only. I hope that helped!

Laura Smith
  • 133
  • 9
  • I feel like your answer is slightly missing the point. Namely the difference between `Integer` and `int`, i.e. wrapper classes. Other than that, it is of course correct. – Zabuzard Jun 02 '21 at 21:19
  • @Zabuzard ah okay, I made edits to my answer to account for that! thanks for letting me know – Laura Smith Jun 02 '21 at 22:34
1
  • In the first example, you are comparing references. In your example, you have two different objects with different references and the same values.

  • In the second example, you are using automatic unboxing which creates new integers in stack memory, and integer comparison which works what you expect. Automatic unboxing can produce NullPointerException in case of null.

Akif Hadziabdic
  • 2,692
  • 1
  • 14
  • 25