Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Integer and int with == [duplicate]

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?

like image 779
Sanskar Dhingra Avatar asked Dec 18 '22 11:12

Sanskar Dhingra


1 Answers

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.

like image 184
Bill the Lizard Avatar answered Dec 30 '22 03:12

Bill the Lizard