Look at the cache problem of integer in Java from source code

Source: Internet
Author: User

Before we start with a detailed explanation of the problem, let's look at a piece of code

1  Public Static void Compare1 () {2         Integer i1 = 127, I2 = 127, i3 = $, i4 =; 3         System.out.println (i1  = = i2); 4         System.out.println (i1.equals (I2)); 5         SYSTEM.OUT.PRINTLN (i3  = = i4); 6         System.out.println (I3.equals (I4)); 7     }

What is the result of this code output?

The answer is:

Was it strange? Why 127 when = = is true,128 when it becomes false? It is not difficult to answer this question.

When an integer is assigned, an auto-boxing operation occurs, and the valueof method of the integer is called, so let's take a look at the Java source Code (1.8):

1 /**2 * Returns an {@codeInteger} instance representing the specified3      * {@codeint} value. If a new {@codeInteger} instance is not4 * required, this method should generally is used in preference to5 * The constructor {@link#Integer (int)}, as this method is likely6 * to yield significantly better space and time performance by7 * caching frequently requested values.8      *9 * This method would always be the cache values in the range-128 to 127,Ten * inclusive, and may caches other values outside the this range. One      * A      * @paramI an {@codeint} value. -      * @returnAn {@codeInteger} instance representing {@codei}. -      * @since1.5 the      */ -      Public StaticInteger ValueOf (inti) { -         if(I >= integercache.low && i <=Integercache.high) -             returnIntegercache.cache[i + (-Integercache.low)]; +         return NewInteger (i); -}

Here according to the source can be seen, in the incoming I value between Integercache.low and Integercache.high, will return the number of Integercache.cache array, not in this range will be new an integer object. Now let's take a look at the initialization of the Integercache array:

1 /**2 * Cache to support the object identity semantics of autoboxing for values between3 * -128 and 127 (inclusive) as required by JLS.4      *5 * The cache is initialized on first usage. The size of the cache6 * May is controlled by the {@code-xx:autoboxcachemax=<size>} option.7 * During VM initialization, Java.lang.Integer.IntegerCache.high property8 * May is set and saved in the private System Properties in the9 * Sun.misc.VM class.Ten      */ One  A     Private Static classIntegercache { -         Static Final intLow =-128; -         Static Final intHigh ; the         Static FinalInteger cache[]; -  -         Static { -             //High value is configured by property +             intH = 127; -String Integercachehighpropvalue = +Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); A             if(Integercachehighpropvalue! =NULL) { at                 Try { -                     inti =parseint (integercachehighpropvalue); -i = Math.max (i, 127); -                     //Maximum array size is Integer.max_value -h = math.min (i, Integer.max_value-(-low)-1); -}Catch(NumberFormatException nfe) { in                     //If The property cannot is parsed into an int, ignore it. -                 } to             } +High =h; -  theCache =Newinteger[(high-low) + 1]; *             intj =Low ; $              for(intk = 0; K < Cache.length; k++)Panax NotoginsengCACHE[K] =NewInteger (j + +); -  the             //range [ -128, 127] must be interned (JLS7 5.1.7) +             assertIntegercache.high >= 127; A         } the  +         PrivateIntegercache () {} -}

We see Integercache's low defined as -128,high, which is defined as 127 by default. But high is configurable, if no configuration is 127. We're not going to look at the configuration, because Java is not configured by default. Look at the cache array, length high-low+1, starting from 128 to 127, in the cache array.

As can be seen from the above code, Java in the application of a number greater than 128 is less than 127, is actually taken from the cache directly to use, if not in this range is new an integer object.

for = =, he compares the address. for int, the comparison is the value.

For Equals, the comparison is the content (depends on the specific implementation of equals). Look at the implementation in the integer:

1 /**2 * Compares this object to the specified object. The result is3      * {@codetrue if and only if the argument are not4      * {@codenull} and is an {@codeInteger} object that5 * Contains the same {@codeint} value as this object.6      *7      * @paramobj The object to compare with.8      * @return  {@codetrue} If the objects is the same;9      *          {@codefalse} otherwise.Ten      */ One      Public Booleanequals (Object obj) { A         if(objinstanceofInteger) { -             returnValue = =((Integer) obj). Intvalue (); -         } the         return false; -}

It does compare the size of the value.

So I1==i2 and I1.equals (I2) are true

I3==i4 to False

I3.equals (I4) is true.

Look at the cache problem of integer in Java from source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.