装箱:将基本类型用他们对应的引用类型包装起来;
拆箱:将包装类型装换为基本类型;
Java基本类型的包装类的大部分都实现了常量池技术,即Byte ,Short,Integer,Long,Character ,Boolean;前面4种包装类默认创建了数值[-128, 127] 的相应类型的缓存数据,两种浮点数类型的包装类Float,Double并没有实现常量池技术。Character创建了数值在[0,127]范围的缓存数据,Boolean直接返回TrueOrFalse。如果超出对应范围仍然会去创建新的对象。
实例
public class Main {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
源码Interge类中valueOf()方法的注释和方法实现(改方法缓存值的范围确定是在-128到127)
java.lang.Integer @Contract(pure = true)
public static Integer valueOf(int i)
返回表示指定int值的Integer实例。 如果不需要新的Integer实例,则通常应优先于构造方法Integer(int)此方法,因为此方法通过缓存经常请求的值可能会产生明显更好的空间和时间性能。 此方法将始终缓存-128至127(包括)范围内的值,并且可能缓存该范围之外的其他值。
参数:
i –一个int值。
返回值:
表示i的Integer实例。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
而其中IntegerCache类的实现为:
java.lang private static class Integer.IntegerCache
extends Object
缓存以支持JLS要求的-128到127(含)之间的值的自动装箱的对象标识语义。 首次使用时会初始化缓存。 缓存的大
小可以由-XX:AutoBoxCacheMax=<size>选项控制。 在VM初始化期间,可以在sun.misc.VM类的私有系统属性中设
置并保存java.lang.Integer.IntegerCache.high属性。
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() {}
}
从这上面的代码可以看出,在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。
其他类型实例(当 "=="运算符的两个操作数都是 包装器类型的引用,则是比较指向的是否是同一个对象,而如果其中有一个操作数是表达式(即包含算术运算)则比较的是数值(即会触发自动拆箱的过程因为Integer对象无法与数值进行比较)。)
class Test3 {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
Long h = 2L;
System.out.println(c == d);
System.out.println(e == f);
System.out.println(c == (a + b));
System.out.println(c.equals(a + b));
System.out.println(g == (a + b));
System.out.println(g.equals(a + b));
System.out.println(g.equals(a + h));
}
}