0

I am using Java ArrayList.

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(-129);
list.add(-129);
return (list.get(0) == list.get(1));

The return value is false. I know it must be some range problem since when I use -128, it returns true. But could someone tell me the reason of it?

Han Li
  • 25
  • 2

3 Answers3

1

Java caches integers in the range -128..127 (signed bytes). It saves a lot of allocations of tiny numbers which is very common in lots of code. If you use equals() instead of ==, it will work. The == check is comparing that two int types, that have been magically boxed (i.e. converted) to Integer are the same reference - which they are not. But int in the signed byte range will be the same. The equals check will actually compare the value of the variables:

return (list.get(0).equals(list.get(1)));
Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
0

When you perform: list.add(-129); list.add(-129);

It create two separate object with separate memory location.when you perform == it return false. In Java, values from -128 to 127 are cached, so the same objects are returned and you will get true.

For more information see:http://www.geeksforgeeks.org/comparison-autoboxed-integer-objects-java/

-1

If two references point to two different objects, then in accordance with the "= =" to judge both is unequal, even though both have the same reference content. As we know, if two references refer to the same object, in accordance with the "= =" to judge the two are equal.

If you go to the Integer. Java classes, you will find that there is a internal private class IntegerCache. Java, it caches from all the Integer object - between 128 ~ 127.

So the thing is, all the small integers are in the internal cache. If the value is between 128 ~ 127, then it will be returned from a cache instance,point to the same object.

HebeleHododo
  • 3,620
  • 1
  • 29
  • 38
Walker
  • 1
  • 1