0

Can someone please explain the internal working of below code snippet

ArrayList<Integer> a = new ArrayList<>(Arrays.asList(902,902));

System.out.println(a.get(0)+" "+a.get(1)+" "+(a.get(0) == a.get(1)));

ArrayList<Integer> b = new ArrayList<>(Arrays.asList(11,11));

System.out.println(b.get(0)+" "+b.get(1)+" "+(b.get(0) == b.get(1)));

Output :

902 902 false
11 11 true

Why the first one is false and the second one is true while the numbers are equal.

Mayur Kharche
  • 697
  • 1
  • 8
  • 27
  • 2
    Integers are boxed reference type, and `==` should not be used to test for equality. It will only work with smaller values that are cached, while larger values are not, and so the `==` test will fail. The links will tell the details. – Hovercraft Full Of Eels Oct 21 '19 at 16:08
  • 2
    Side note: terrible question title by the way as it gives no clue as to the nature of your question. You will want the title to summarize the problem in an *informative* way, much like a newspaper headlines summarizes the article below. – Hovercraft Full Of Eels Oct 21 '19 at 16:10
  • It will only work for smaller integer value -128 to 127. So as soon as you will increase the value to 128 it starts failing. Mainly, the Integer class keeps a cache for smaller value. – Harshit Oct 21 '19 at 16:57

0 Answers0