Java中每个基本类型都有一个包装类。例
byte → Byte
short → Short
int → Integer
long → Long
float → Float
double → Double
char → Character
boolean→ Boolean
基本类型转换为包装类类型:装箱
//装箱
int a = 100;
Integer a1 = Integer.valueOf(a);
System.out.println(a1);
源码分析:
//Integer包装类的方法
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果传入的值在[-128,127]之间则,则不需要重新创建Integer对象。否则重新创建一个Integer对象。
IntegerCache是Integer的静态内部类,在static静态代码块中创建了一个范围为[-128,127],类型为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;
//创建一个范围为[-128,127]大小,类型为Integer的数组
//创建256个Integer类型的对象赋给数组元素
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() {}
}
包装类类型转换为基本类型:拆箱
//拆箱
Integer b = 100;
int b1 = b.intValue();
System.out.println(b1);
源码:直接返回包装类中的value的值。
public int intValue() {
return value;
}
128陷阱分析:
Integer a = 100;
Integer b = 200;
int a1 = 100;
int b1 = 200;
Integer c = 100;
Integer d = 200;
System.out.println(a==a1);
System.out.println(b==b1);
System.out.println(a==c);
System.out.println(b==d);
输出结果:
true
true
true
false
结果分析:
System.out.println(a==a1): 包装类a的value值为100,和a1的值相等。所以结果为true。同理,
System.out.println(b==b1); 的结果为true。
System.out.println(a==c): a和c均为包装类,且值都为100,在[-128,127]之间,所以引用的均为IntegerCache类中cache数组中的对象,在初始化时已经创建好。结果为true。
System.out.println(b==d): b和d均为包装类,且值都为200,在[-128,127]之外,它们都会创建新的Integer对象。结果为false。