首先感谢http://my.oschina.net/heguangdong/blog/141053 博文的提示。 java
装箱调用的是valueOf()方法(应该是编译器执行的)。仍是拿Long类型举例(Integer是同样的) spa
源码以下: .net
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); }而LongCache中维护了-128到127的一个常量池,故这些常量对象只会一份不会再new。
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); } }让咱们再看看Double的源码:
public static Double valueOf(double d) { return new Double(d); }每次都是new 的一个对象。这样就解释了为何Double型不能用==的缘由。
另外得注意Long Integer类型使用==的条件。(-128到127) code