java 自动拆箱的圈套

java 自动拆箱的陷阱

先看代码

 public class IntegerDemo {
	public static void main(String[] args) {

		Integer a = 1;
		Integer b = 1;

		Integer c = 128;
		Integer d = 128;
		Integer.valueOf(a);

		System.out.println(a==b);
		System.out.println(c==d);
	}
}


输出是什么

如果不看源码,你肯定想不到结果。对象 a 和 b的地址相同,对象 c和 d 的地址相同,操作符 ==  就是比较地址的,自然都是true,但是结果却不是这样。

程序输出
true
false

为什么呢,
当把int值 赋给 Integer的时候  会自动调用 valueOf 方法,生成Integer对象
对象 a 和 b 的地址是一样的,所以返回true

我们先来看看源码

public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }


先来解读一下 java 规定 IntegerCache.high = 127
传入的值 在 -128 到 127 之间的时候,就返回 IntegerCache.cache[i + 128];
由于数组下标是从0开始,从 -128开始,刚好对上。

但是当 传入的值  不在 -128 到 127 之间的时候,就会实例化另外一个对象返回,自然输出false。

在传递参数的时候,经常忽略int 和Integer 的区别,如果超出限制,往往会创建大量的对象,浪!费!

在以 Integer 为key 的HashMap 中,如果忽略了这个大小限制,那就会创建大量的空白空间,但是又不知道是怎么回事。
浪!费!

long 的源码 也是这样

public static Long valueOf(long l) {
	final int offset = 128;
	if (l >= -128 && l <= 127) { // will cache
	    return LongCache.cache[(int)l + offset];
	}
        return new Long(l);
    }


double Float 不是

 public static Double valueOf(double d) {
        return new Double(d);
    }


其他的 自己查看。