The cache for integer

Source: Internet
Author: User

How to get an integer instance based on the integer class:

Integer instance=new integer (int value);

Integer instance=integer.valueof (int value);

The first approach will certainly produce a new instance each time, but the second way is not:

1  Public Static voidMain (String[]args) {2Integer i1=integer.valueof (127);3Integer i2=integer.valueof (127);4System.out.println (i1==i2);5         6Integer i3=integer.valueof (128);7Integer i4=integer.valueof (128);8System.out.println (i3==I4);9         TenInteger i5=integer.valueof (-128); OneInteger i6=integer.valueof (-128); ASystem.out.println (i5==I6); -          -Integer i7=integer.valueof (-129); theInteger i8=integer.valueof (-129); -System.out.println (i7==i8); -}
Truefalsetruefalse

This result is caused because the integer class internally caches an instance of the range [-128,127] of the value of 128 to 127.

Similar to the following code:

1  Public classTest {2      Public Static voidMain (String[]args) {3Myinteger i1=myinteger.valueof (10);4Myinteger i2=myinteger.valueof (10);5System.out.println (i1==i2);6         7Myinteger i3=myinteger.valueof (11);8Myinteger i4=myinteger.valueof (11);9System.out.println (i3==I4);Ten     } One } A  - classMyinteger { -     Private Final intvalue; the      PublicMyinteger (intvalue) { -          This. value=value; -     } -      Public StaticMyinteger ValueOf (inti) { +myinteger[]caches=MyInteger.MyIntegerCache.caches; -         if(i>=1&&i<=10) { +             returnCaches[i-1]; A         } at         return NewMyinteger (i); -     } -      -     Static classMyintegercache { -         Staticmyinteger[]caches=NewMyinteger[10]; -         Static { in              for(inti=0;i<10;i++) { -caches[i]=NewMyinteger (i+1); to             } +         } -     } the}

The cache for integer

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.