在这个范围内,系统会自动为这范围内的每一个整数缓存对象,这范围的每一个相同的数字对应的Integer对象所对应的引用都是相等的,因为指向的对象都是一个,而这范围之外的就没有这种缓存。也就和正常的引用一样,因为指向的是不同的对象,所以不相等,这样做的原因是为了加快系统效率。

解决方案 »

  1.   

    Cache to support the object identity semantics of autoboxing for values between  -128 and 127 (inclusive) as required by JLS.
      

  2.   

    这个问题出现很多次了,Integer缓存了-128~127之间的数,这是在类加载期间就完成的。以后需要的时候直接指向它就可以了,省去了构造对象的开支,提高了效率。
      

  3.   

    Integer 源码    private static class IntegerCache {
            static final int low = -128;
            static final int high;
            static final Integer cache[];    public static Integer valueOf(int i) {
            assert IntegerCache.high >= 127;
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }Integer 缓存-128 ~ 127 之间的数字,范围外的就只能去new了
      

  4.   

    介于-128~127的int,包装到固定的Integer对象,就是e,f包装到了同一个Integer对象,==比较的是引用,所以是true。不在这之间的,e,f分别指向了包装到了不同的Integer对象,所以是false