面试时经常被问到Integer i=127和Integer j=127的区别?
java 1.5 的自动装箱拆箱机制是编译特性还是虚拟机运行时特性?分别是怎么实现的?
本文章以Integer为例说明java包装类缓存池的问题(摘自JDK1.8源码)
1. 打印输出
- Integer(有)
Integer a=1;
Integer b=1;
Integer a1=new Integer(1);
Integer b1=Integer.valueOf(1);
System.out.println(a==b); //true
System.out.println(a==a1); //false
System.out.println(a==b1); //true
System.out.println(a1==b1); //false
直接赋值采用的是java的自动装箱机制(语法糖),经过反编译后可以看到直接赋值的方式采用的就是Integer.valueOf().
那为什么a和b1比较是true呢?为什么a和b也相等呢? 查看
- Short(有)
Short c=2;
Short d=2;
System.out.println(c==d); //true
- Byte(有)
Byte e=3;
Byte f=3;
System.out.println(e==f); //true
- Character(有)
Character g='c';
Character h='c';
System.out.println(g==h); //true
- Long(有)
Long i=4L;
Long j=4L;
System.out.println(i==j); //true
- Float(无)
Float float1=0.2F;
Float float2=0.2F;
System.out.println(float1==float2); //false
- Double(无)
Double double1=0.1;
Double double2=0.1;
Double double3=Double.valueOf(0.1);
Double double4=new Double(0.1);
System.out.println(double1==double2); //false
System.out.println(double1==double3); //false
System.out.println(double1==double4); //false
System.out.println(double3==double4); //false
- Boolean(无)
Boolean boolean1=true;
Boolean boolean2=true;
Boolean boolean3=new Boolean(true);
Boolean boolean4=Boolean.valueOf(true);
System.out.println(boolean1==boolean2); //true
System.out.println(boolean1==boolean3); //false
System.out.println(boolean1==boolean4); //true
2. 源码分析
-
Integer(有) 范围[-128-127]
//new Integer时调用的构造函数 new Integer(1)调用的是此构造函数
public Integer(int value) {
this.value = value;
}
//自动装箱机制
public static Integer valueOf(int i) { Integer i 和Integer.valueOf()赋值时执行的方法
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(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() {}
}
- Short(有)[-128-127]
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}
- Byte(有)[-128-127]
private static class ByteCache {
private ByteCache(){}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128));
}
}
- Character(有)[0-127] Ascii码目前128个
private static class CharacterCache {
private CharacterCache(){}
static final Character cache[] = new Character[127 + 1];
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
}
- Long(有) 范围[-128-127]
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);
}
}
- Float(无)
public Float(float value) {
this.value = value;
}
public static Float valueOf(String s) throws NumberFormatException {
return new Float(parseFloat(s)); //自动拆箱每次new一个新的对象
}
- Double(无)因为在指定范围内浮点型数据个数是不确定的,所以不能使用cache
public Double(double value) {
this.value = value;
}
public static Double valueOf(String s) throws NumberFormatException {
return new Double(parseDouble(s)); //自动拆箱每次new一个新的对象
}
- Boolean(无)
public Boolean(boolean value) {
this.value = value;
}
public static Boolean valueOf(String s) {
return parseBoolean(s) ? TRUE : FALSE;
}
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
3. 总结
通过源码可以看到,Integer包装类的缓存和其他的不太相似,它的范围值默认情况下是[-128-127],可以根据需要改变虚拟机参数-XX:AutoBoxCacheMax=size来调整范围。
我们在日常开发中,如果要比较包装类值的大小,必须使用equals方法,禁止使用==。
面试题赏析
java 是否存在使得语句 i > j || i <= j 结果为 false 的 i、j 值?
Double m=0.2d; Double n=Double.NaN; System.out.println(m>n||m<=n);//false
java 的数值 NaN 代表 not a number,无法用于比较: public static final double NaN = 0.0d / 0.0;
java 1.5 的自动装箱拆箱机制是编译特性还是虚拟机运行时特性?分别是怎么实现的?
1.java1.5开始的自动装箱拆箱机制其实是编译时自动完成替换的,装箱阶段自动替换为了valueOf方法,拆箱阶段自动替换为了 xxxValue方法。
2.对于 Integer 类型的 valueOf 方法参数如果是-128~127之间的值会直接返回内部缓存池中已经存在对象的引用,参数是其他范围值则返回新建对象;
3.Double 类型一样会调用 Double 的 valueOf 方法,但是 Double 的区别在于不管传入的参数值是多少都会 new 一个对象来表达该数值.
注意:
Integer、Short、Byte、Character、Long 的 valueOf 方法实现类似。
而 Double 和 Float 比较特殊,每次返回新包装对象。
对于两边都是包装类型的比较 == 比较的是引用,equals比较的是值。
对于两边有一边是表达式(包含算数运算),== 比较的是数值(自动触发拆箱过程)。
对于包装类型 equals 方法不会进行类型转换。