Java包装器相等性测试 [英] Java Wrapper equality test
问题描述
public class WrapperTest {
public static void main(String[] args) {
Integer i = 100;
Integer j = 100;
if(i == j)
System.out.println("same");
else
System.out.println("not same");
}
}
上面的代码在运行时给出了same
的输出,但是,如果我们将i
和j
的值更改为1000,则输出将更改为not same
.在为SCJP进行准备时,需要弄清楚这一概念.有人可以解释这种行为.谢谢.
The above code gives the output of same
when run, however if we change the value of i
and j
to 1000 the output changes to not same
. As I'm preparing for SCJP, need to get the concept behind this clear. Can someone explain this behavior.Thanks.
推荐答案
在Java中,-128至127(含)之间的整数通常由相同的Integer对象实例表示.这可以通过使用称为IntegerCache的内部类(包含在Integer类中,并在例如调用Integer.valueOf()时或在自动装箱期间使用)来处理:
In Java, Integers between -128 and 127 (inclusive) are generally represented by the same Integer object instance. This is handled by the use of a inner class called IntegerCache (contained inside the Integer class, and used e.g. when Integer.valueOf() is called, or during autoboxing):
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);
}
}
另请参见: http://www.owasp.org/index.php/Java_gotchas
这篇关于Java包装器相等性测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!