0

I want to compare two elements in an ArrayList == operator, I write this code:

ArrayList<Integer> myArray=new ArrayList<>();
myArray.add(-128);
myArray.add(-128);
System.out.println(myArray.get(0)==myArray.get(1));

I get true as result, but with other value like:

myArray.add(2000);
myArray.add(2000);
System.out.println(myArray.get(0)==myArray.get(1));

I get false as result.

I know that == operator Compares references, not values, in this case the two Integers have different references, so logically we must have false for both case. I don't understand Why I get true for only an Integer from -128 to 127 and false for other Integer.

NB: I see many questions in Stackoverflow and Google, but I can't find an answer of my question

Mourad BENKDOUR
  • 879
  • 2
  • 9
  • 11
  • 3
    http://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127 – Sotirios Delimanolis Nov 18 '15 at 22:54
  • Ok I see that: For values between the range of -128 to 127 Java points all the Integer/ int references to the same object to save memory. for more details http://bexhuff.com/2006/11/java-1-5-autoboxing-wackyness – Mourad BENKDOUR Nov 18 '15 at 23:15

1 Answers1

0

The values in range -128 -> 127 are cached in Integer class.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417