包装类(类)
常见问题:
/* 1、常见问题 */
Integer i1 = 127;
int i2 = 127;
Integer i3 = Integer.valueOf(127);
Integer i4 = new Integer(127);
Integer i5 = 128;
Integer i6 = Integer.valueOf(128);
System.out.println(i1 == i2); // true 因为i2是基本数据类型 所以比较时 会将i1 转成基本数据类型 比较二者的值
System.out.println(i2 == i3); // true 同上 Integer.valueOf(127) 就是将127 转成包装类
System.out.println(i1 == i3); // true Integer内部维护了一个范围[-128~127]的缓冲区,如果值在这个范围内会直接返回缓冲区中的对象,所以为true
System.out.println(i5 == i6); // false 取值范围不在缓冲区中,将会创建新的对象。
System.out.println(i1 == i4); // false 因为new 关键字会在堆中开辟出一片新的空间所以i4 和 i1 存的引用并不相同
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() {}
}
Long的缓存类实现:
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
定义了两个静态常量,使用的16进制。
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000; // -2147483648
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff; // 2147483647
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}