Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: wrong behaviour when checking the equality of two elements of an ArrayList<Integer> using the operator "=="



Francesca De Angeli wrote:

>Now imagine to do the following:
>
>int myPrimitiveInt = 4;
>ArrayList<Integer> list = new ArrayList<Integer>();
>list.add(myPrimitiveInt);
>list.add(myPrimitiveInt);
>
>What really surprises me is that now you will get true from the condition
>(list.get(0) == list.get(1)) !
>This is really unexpected as the method ArrayList.get(int) returns an
>Integer object not a primitive and the == operator should check if the two
>objects are the same and not if their value is the same.

You are running into a side-effect of auto-boxing.  The effect you call
unexpected is, in fact, expected, given the example.

When small constant ints are auto-boxed, there is a certain range for which
a single instance of Integer is reused for every appearance of that numeric
value.  I think the range is -100 to 100, or thereabouts.  Outside the
range, the compiler will use separate objects.  Inside the range, it reuses
a single pre-existing object for each numeric value.  The principle is
similar to String.intern(), but you have no control over it.

Therefore, given that your value is 4, and it's known at compile-time, the
compiler can compile a reference to a single Integer whose int-value is 4.
So in fact, you ARE getting the correct result from ==, because your code
is equivalent to this:

  Integer four = new Integer(4);
  ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(four);
  list.add(four);

Note the difference with what you think is the equivalent, but which really
isn't:

  int myPrimitiveInt = 4;
  ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(new Integer(myPrimitiveInt));
  list.add(new Integer(myPrimitiveInt));

I suggest two experiments:
  1) Disassemble the auto-boxed code, to see what's really getting put into
the array-list.

  2) Vary the range of small constants that you put into the array-list, to
find the end-points of the range the compiler uses singleton Integers for.


Is the fact that == returns true a problem, or simply a curiosity?  If it's
a problem, please explain how it's a problem.

  -- GG


 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Java-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/java-dev/email@hidden

This email sent to email@hidden



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.