Integercache inner class for Java integer encapsulation class

Source: Internet
Author: User
Tags true true

Personal understanding, do not like to spray, welcome correction.

First look at the following code, guess what the output is

1         Integer a = ten; 2         Integer B = Ten; 3         System.out.println (A = = b); 4         A = +; 5         b = +; 6         System.out.println (A = = b); 7         A = +; 8         b = +; 9         System.out.println (A = = B);    

Do you think true true True or false false?

Naïve, look.

You're right, that's the hole!

In a logical case, Integer is the package type, and the result should be false false.

So let's see how this code executes, and that's what happens.

First, when you assign a value, the following function is called, and here comes a strange thing, integercache, it looks like the problem is here.

Next look at what the Integercache is what, the following is the source of the class

In the source code we see this class has a [-128,127] integer array cache (the upper bound of this array seems to be variable, but I do not have RT source package, so I do not know the details), so look at the integer assignment code, it is very clear

This determines whether the size of your assignment is contained within the Integercache cache array.

If a reference to the object is returned, and thus less than or equal to 127 is greater than or equal to-128, the result can be obtained by = = Comparison to True, because the reference is the same, The number of out-of-range calls the integer constructor to recreate an integer object so that the value is the same but the result is false due to a different reference

So judging whether the object's value is the same or using a.equals (b)

Integercache inner class for Java integer encapsulation class

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.