Integer对象的==比较

1.

Integer a = 127;
Integer b = 127;
System.out.println(a.hashCode()==b.hashCode());
System.out.println(a==b);
System.out.println(a.equals(b));

 结果为:

true
true
true

 2.

Integer a = 128;
Integer b = 128;
System.out.println(a.hashCode()==b.hashCode());
System.out.println(a==b);
System.out.println(a.equals(b));

 结果为:

true
false
true

 都是==比较,为什么一个true,一个false呢?

结论:

Integer==比较,最终会走到IntegervalueOf方法。

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

其中IntegerCache.high =128

 

如果要比较的值,在-128—127之间,走的就是IntegerCache,那么比较结果==就是相等的

如果要比较的值,不在-128—127之间,走的就是 new Integer(i)==结果就不一样了。

 

附上 IntegerCache的源码:

private static class IntegerCache {
        static final int high;
        static final Integer cache[];

        static {
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - -low);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }
posted @ 2015-09-02 11:48  fanning  阅读(431)  评论(0)    收藏  举报