1 public static void main(String[] args) { 2 Integer a=100; 3 Integer a1=100; 4 Integer b=200; 5 Integer b1=200; 6 Integer c=new Integer(300); 7 Integer c1=new Integer(300); 8 System.out.println(a==a1);//true 9 System.out.println(b==b1);//false 10 System.out.println(c==c1);//false 11 System.out.println(c.equals(c1));//true 12 }
1 public static Integer valueOf(int i) { 2 if (i >= IntegerCache.low && i <= IntegerCache.high) 3 return IntegerCache.cache[i + (-IntegerCache.low)]; 4 return new Integer(i); 5 }
1 private static class IntegerCache { 2 static final int low = -128; 3 static final int high; 4 static final Integer[] cache; 5 static Integer[] archivedCache; 6 static { 7 // high value may be configured by property 8 int h = 127; 9 String integerCacheHighPropValue = 10 VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); 11 if (integerCacheHighPropValue != null) { 12 try { 13 h = Math.max(parseInt(integerCacheHighPropValue), 127); 14 // Maximum array size is Integer.MAX_VALUE 15 h = Math.min(h, Integer.MAX_VALUE - (-low) -1); 16 } catch( NumberFormatException nfe) { 17 // If the property cannot be parsed into an int, ignore it. 18 } 19 } 20 high = h; 21 // Load IntegerCache.archivedCache from archive, if possible 22 VM.initializeFromArchive(IntegerCache.class); 23 int size = (high - low) + 1; 24 // Use the archived cache if it exists and is large enough 25 if (archivedCache == null || size > archivedCache.length) { 26 Integer[] c = new Integer[size]; 27 int j = low; 28 for(int i = 0; i < c.length; i++) { 29 c[i] = new Integer(j++); 30 } 31 archivedCache = c; 32 } 33 cache = archivedCache; 34 // range [-128, 127] must be interned (JLS7 5.1.7) 35 assert IntegerCache.high >= 127; 36 } 37 private IntegerCache() {} 38 }
1 public boolean equals(Object obj) { 2 if (obj instanceof Integer) { 3 return value == ((Integer)obj).intValue(); 4 } 5 return false; 6 }
原文:https://www.cnblogs.com/majortom/p/12860527.html