Java Basics------The difference between New Integer (1) and integer.valueof (1)

Source: Internet
Author: User
Tags static class

The integer class in the Java.lang package is one of our more common classes, such as the following code:

Integer a=new integer (1)

Integer a=integer.valueof (1);

All two get an integer object, but the integer.valueof is highly efficient. Why, then? Because integer.valueof used the caching mechanism.

Where the Integer.valueof method code is as follows:

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);
}

A helper class Integercache is used in this class, where the source code for Integercache is as follows:

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);
}
}

You can see that the cache array has been initialized in Integercache. So, note that the new integer returns a different object forever, but when the integer range is -128<i<=127, INTEGER.VALUEOF returns the same object.

Look at the following code:

Integer a=new integer (1);
Integer b=new integer (1);

Integers range from 128 to 127 and return the same object
Integer c=integer.valueof (1);
Integer d=integer.valueof (1);

Not the same object returned
Integer e=integer.valueof (200);
Integer f=integer.valueof (200);

System.out.println (A==B);
System.out.println (C==d);
System.out.println (E==F);

The results of the program running are:

False

True

False

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.