標籤:
根據Integer類得到Integer執行個體的方式:
Integer instance=new Integer(int value);
Integer instance=Integer.valueOf(int value);
第一種方式每次當然都會產生一個新的執行個體,但是第二種方式就不盡然:
1 public static void main(String[]args) { 2 Integer i1=Integer.valueOf(127); 3 Integer i2=Integer.valueOf(127); 4 System.out.println(i1==i2); 5 6 Integer i3=Integer.valueOf(128); 7 Integer i4=Integer.valueOf(128); 8 System.out.println(i3==i4); 9 10 Integer i5=Integer.valueOf(-128);11 Integer i6=Integer.valueOf(-128);12 System.out.println(i5==i6);13 14 Integer i7=Integer.valueOf(-129);15 Integer i8=Integer.valueOf(-129);16 System.out.println(i7==i8);17 }
truefalsetruefalse
之所以會導致這種結果,是因為Integer類內部對value值為-128到127範圍[-128,127]的執行個體緩衝了下來。
類似如下代碼:
1 public class Test { 2 public static void main(String[]args) { 3 MyInteger i1=MyInteger.valueOf(10); 4 MyInteger i2=MyInteger.valueOf(10); 5 System.out.println(i1==i2); 6 7 MyInteger i3=MyInteger.valueOf(11); 8 MyInteger i4=MyInteger.valueOf(11); 9 System.out.println(i3==i4);10 }11 }12 13 class MyInteger {14 private final int value;15 public MyInteger(int value) {16 this.value=value;17 }18 public static MyInteger valueOf(int i) {19 MyInteger[]caches=MyInteger.MyIntegerCache.caches;20 if(i>=1&&i<=10) {21 return caches[i-1];22 }23 return new MyInteger(i);24 }25 26 static class MyIntegerCache {27 static MyInteger[]caches=new MyInteger[10];28 static {29 for(int i=0;i<10;i++) {30 caches[i]=new MyInteger(i+1);31 }32 }33 }34 }
Integer的緩衝