Integer比较时的True or False问题
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 }
首先需要明确一点,Java中的==比较如果比较的是基本数据类型,会把数据从常量池里面取出进行比较;比较引用数据类型时,则会比较其引用的地址是否相同。
再说回第一行代码,Integer a=100实质上是Integer a=Integer.valueof(100),而查看valueof方法的源码
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 }
再查看IntegerCatch的定义源码
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 }
可以看出,Java内部维护了一个缓存数组catch,而这个数组的范围是-128到127。所以说,当使用Integer a=xx的形式进行赋值时,若赋的值在-128到127之间,并不创建新对象,即引用的地址始终相同,所以比较的结果为true;若赋的值不在在-128到127之间,则此语句等效于Integer a=new Integer(xx),此时地址自然不同,结果自然为false。
而对于最后一行的equals比较,查看equals的源码
1 public boolean equals(Object obj) { 2 if (obj instanceof Integer) { 3 return value == ((Integer)obj).intValue(); 4 } 5 return false; 6 }
可以看出,若比较的双方为同一数据类型时,其比较的仍是具体的数值,所以比较的结果自然为true。

浙公网安备 33010602011771号