First look at the following example:
Public class testnew { publicstaticvoid main (String args[]) { = ten; //Integer i1 = integer.valueof (ten); Integer i2 = ten; = +; = +; = = i2) ; = = i4);} }
Where the comment is used to represent the compiler after the optimization of the code, the description should be for i1 = 10 assignment, because it is a wrapper class, so to create an integer object, so that the last two objects of the address comparison, the result is false, but the real result is not.
true false 0
The result of the first comparison is true, in order to find out why, it is necessary to look at the specific implementation of the ValueOf method of Integer.
/*** Returns an {@codeInteger} instance representing the specified * {@codeint} value. If a new {@codeInteger} instance is isn't * required, this method should generally being used in preference to * the constructor {@link#Integer (int)}, as this method was likely * to yield significantly better space and time performance by * Cach ing frequently requested values. * This method would always have the cache valuesin the range-128 to 127, * inclusive, and could cache other value s outside of this range. * * @paramI an {@codeint} value. * @returnAn {@codeInteger} instance representing {@codei}. *@since1.5*/ Public StaticInteger ValueOf (inti) {assertIntegercache.high >= 127; if(I >= integercache.low && i <=Integercache.high)returnIntegercache.cache[i + (-Integercache.low)]; return NewInteger (i); }
As can be seen here, for value int value between 128 and 127, when this method is called to create an integer object, it is returned directly from the buffer pool, if there is a buffer pool, then the same object is returned.
If, at this point, the i2 is assigned a value of 1, will the I1 also become 1?
The answer is no, the wrapper class in the previous article, the parameter passing problem is similar to this, because the 1 is assigned to I2, this time 1 is automatically boxed as an integer object, and let I2 point to the new object, so this will not change I
The value.
Buffer pool problem for "Java Basics" Integer wrapper class