java - Integer != 1 何时成立

标签 java

这很经典,但写信给 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/

相关文章:

java - Kafka 0.11 中 sendOffsetsToTransaction 的含义

用于加密/解密的 Java SimpleCrypto 类在 Coldfusion 9 和 Java (Android) 中产生不同的结果

java - 如何查看包含我的方法生成的帧的 strackrace?

java - 在 DNS 重定向错误的情况下,发送的正确 HTTP 响应是什么?

java - Windows -cp Mainclass 无法加载

java - JTree显示问题

java - Android Studio登录系统数据库问题

java - 在 Java 中创建一个 ArrayList?

java/ eclipse : starting a new JVM in Debug mode

java swing GroupLayout - 如何交换组件的位置