代码如下:
/** * @comment:Integer 类型数值比较 * @author:傅里叶级数 * @date:2018年8月 * @param args */ public static void main(String[] args) { Integer a =127; Integer b = 128; Integer c =127; Integer d =128; Integer e=-128; Integer f = -128; Integer g = -129; Integer h = -129; //打印int类型的hash值: System.out.println(System.identityHashCode(a));//644117698 System.out.println(System.identityHashCode(c));//644117698 System.out.println(System.identityHashCode(h));//1872034366 System.out.println(System.identityHashCode(g));//1581781576 System.out.println(a==c);//true System.out.println(b==d);//false System.out.println(f==e);//true System.out.println(g==h);//false }
源码解释:
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
综上,如果两个Integer的值在[-128,127]之间,==比较返回值为true;否则可能(may)new一个对象,hash地址不同,==返回false。