Java record-76-Integer cache

Source: Internet
Author: User

Java record-76-Integer cache
There is a simple example of Integer in the Integer cache, but the output result is unexpected:

public class IntegerTest2 {    public static void main(String[] args){        Integer i1 = 100;        Integer i2 = 100;        System.out.println(i1 == i2);                 Integer i3 = 200;        Integer i4 = 200;        System.out.println(i3 == i4);    }}

 

The output results of the above instance are true and false. Why? A little incredible... next, we can analyze the source code of Integer (for example, we can only view and analyze the cause of this problem through the source code); look at the valueOf method of Integer, this method converts an int value to an Integer, but when the int value is greater than-128 and less than 127, it must cache the must cache and return the value in the cache array of IntegerCache; we are looking at IntegerCache, which is an internal class of Integer. It defines a static array of Integer types and initializes the value cyclically in the static block. That is to say, if we use Integer to obtain objects greater than-128 and less than 127, all returned objects are cached and are not generated.
    public static Integer valueOf(int i) {        final int offset = 128;        if (i >= -128 && i <= 127) { // must cache             return IntegerCache.cache[i + offset];        }            return new Integer(i);    }    private static class IntegerCache {        private IntegerCache(){}             static final Integer cache[] = new Integer[-(-128) + 127 + 1];             static {            for(int i = 0; i < cache.length; i++)            cache[i] = new Integer(i - 128);        }    }

 

The jdk api documentation prompts: public static Integer valueOf (int I) if a new Integer instance is not required, this method should be used first instead of the Construction Method Integer (int ), this method may significantly improve the space and time performance by caching frequently requested values.

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.