Java 为每个原始类型提供了包装类型:
- 原始类型: boolean,char,byte,short,int,long,float,double
- 包装类型:Boolean,Character,Byte,Short,Integer,Long,Float,Double
Integer与int的区别最基本的是:Ingeter是int的包装类,int的初值为0,Ingeter的初值为null
1.自动拆箱比较为true
@org.junit.Test
public void testInteger() {
int a1 = 128;
Integer a2 = 128;
Integer a3 = new Integer(128); // 这样写优化后其实就是a2的写法
// Integer会自动拆箱为int,所以为true
System.out.println("a1 == a2: " + (a1 == a2)); // true a1和a2为Integer对象,所以判断相等最好用equals
System.out.println("a1 == a3: " + (a1 == a3)); // true
}
2.缓存区间的数比较为true
@org.junit.Test
public void testInteger() {
Integer c1 = 128;
Integer c2 = 128;
System.out.println("c1 == c2: " + (c1 == c2));//false
Integer b1 = 127;//java在编译的时候,被翻译成-> Integer i5 = Integer.valueOf(127);
Integer b2 = 127;
System.out.println("b1 == b2: " + (b1 == b2));//true
}
看valueOf()函数了。JDK源码的valueOf函数式这样的
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache是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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
看一下源码大家都会明白, 对于-128到127之间的数,会进行缓存,Integer b1= 127时,会将127进行缓存,下次再写Integer b2= 127时,就会直接从缓存中取,就不会new了。
3.都new出来的对象比较为false
@org.junit.Test
public void testInteger() {
Integer d1 = new Integer(127);
Integer d2 = 127;
System.out.println("d1 == d2: " + (d1 == d2)); //false
Integer e1 = new Integer(128);
Integer e2 = new Integer(123);
System.out.println("e1 == e2: " + (e1 == e2)); //false
}
①无论如何,Integer与new Integer不会相等。不会经历拆箱过程,d1的引用指向堆,而d2指向专门存放他的内存(常量池),他们的内存地址不一样,所以为false
②两个都是非new出来的Integer,如果数在-128到127之间,则是true,否则为false
java在编译Integer c2= 128的时候,被翻译成-> Integer c2= Integer.valueOf(128);而valueOf()函数会对-128到127之间的数进行缓存
③两个都是new出来的,都为false
④int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比