这很经典,但写信给 Google 并没有给我带来点击。
我的代码:
Integer i = ..; // Sth is put from database.
if (i != 1) {
// do sth
} else {
// do not.
}
案例:
我知道这个比较不正确 java
我应该比较:
if (i.intValue != 1) {}
或
if(!i.equals(1)) {}
但我的代码有第一个,我似乎从某个地方得到了真实的,其中 Integer
不为 1,为 1 时为 false。
问题:
周围发生了什么?
最佳答案
but my code had the first one and I seem to get the true from somewhere, where the Integer is not 1 and when it is 1 there comes false.
如果我正确理解您的问题,以下内容可能会解释该行为:
Integer i = 1;
Integer j = new Integer(1);
Integer k = Integer.valueOf(1);
System.out.println(i == j); // false
System.out.println(i == k); // true
换句话说,与 1
进行比较时,您可能会得到 true 或 false,具体取决于 Integer
的构造方式。 Integer.valueOf
将重用对象,而 new Integer
则不会。
如果您确实与整数文字(或 int
)进行了比较,那么任何 Integer
都应该被编译器自动拆箱,并且您永远不应该得到任何惊喜。
关于java - Integer != 1 何时成立,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890906/