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