为什么比较两个整数使用==有时工作,有时不工作?
我知道我正在比较参考,而我正在使用==这不是一个好主意,但我不明白为什么会发生这种情况。
Integer a=100; Integer b=100; Integer c=500; Integer d=500; System.out.println(a == b); //true System.out.println(a.equals(b)); //true System.out.println(c == d); //false System.out.println(c.equals(d)); //true
Java语言规范说至少-128到127的包装器对象被Integer.valueOf()
缓存并重用,这是自动装箱隐式使用的。
缓存-128和127之间的整数(相同值的整数引用相同的Object
)。 比较a
和b
引用返回true
,因为它们是相同的Object
。 您的c
和d
不在该范围内,因此它们的引用比较返回false
。
正在缓存-128到127之间的整数值。
请参阅以下源代码:
private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } } public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); }