看面试题的时候看到这道题:
public class Demo { public static void main(String[] args) { Integer i1 = 128; Integer i2 = 128; System.out.println((i1.equals(i2))); System.out.println((i1==i2)); Integer i3 = 100; Integer i4 = 100; System.out.println((i3.equals(i4))); System.out.println((i3==i4)); } }
这运行出来是:
true false true true
从这个结果可以知道,i1和i2不是同一个对象,而i3和i4会是同一个对象。
那么可以从哪里下手呢?
可以从Integer的源码里面找到答案:
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
如果传入的参数i的值在一个范围里面,那么就先改造一下这个参数然后返回回去,如果超过了这个范围就创造一个新的Integer对象。
那么先来看一下这个范围是什么。
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }
可以知道,IntegerCache.low是直接定义好的了,就是-128,但是IntegerCache.high还需要再经过一定的流程来决定,一般来说应该是一个大于或等于127的数。
综上所述,一般来说,Integer创建的对象的值如果是在[-128,127]之内的,创建的值是相同的对象那就是同一个对象(当然如果值在后续操作改变了那就不是同一个对象了);但是如果是在这个范围之外的话,Integer对象就会创建新的对象。