java - 如何正确比较 Java 中的两个整数?

标签 java integer autoboxing

我知道,如果您将装箱的原始整数与常量进行比较,例如:

Integer a = 4;
if (a < 5)

a 将自动被拆箱,并且可以进行比较。

但是,当您比较两个装箱的 Integers 并想要比较相等或小于/大于时会发生什么?

Integer a = 4;
Integer b = 5;

if (a == b)

上面的代码会检查它们是否是同一个对象,还是会在这种情况下自动拆箱?

怎么样:

Integer a = 4;
Integer b = 5;

if (a < b)

?

最佳答案

否,Integer、Long 等之间的 == 将检查 引用相等性 - 即

Integer x = ...;
Integer y = ...;

System.out.println(x == y);

这将检查 xy引用相同的对象而不是相等的对象。

所以

Integer x = new Integer(10);
Integer y = new Integer(10);

System.out.println(x == y);

保证打印false . “小”自动装箱值的实习可能会导致棘手的结果:

Integer x = 10;
Integer y = 10;

System.out.println(x == y);

这将打印 true , 由于拳击规则 (JLS section 5.1.7)。它仍然使用引用相等,但引用真正相等的。

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

我个人会使用:

if (x.intValue() == y.intValue())

if (x.equals(y))

如您所说,对于包装器类型(IntegerLong 等)和数字类型(intlong 等)之间的任何比较,包装器类型值是未装箱 并且测试应用于所涉及的原始值。

这发生在二进制数字提升 (JLS section 5.6.2) 中。查看每个运算符(operator)的文档以查看它是否已应用。例如,来自 == 的文档和 != (JLS 15.21.1):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

对于 < , <= , >>= (JLS 15.20.1)

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

请注意,在两种类型都不是数字类型的情况下,这些都不被视为的一部分。

关于java - 如何正确比较 Java 中的两个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1514910/

相关文章:

java - Java 中的 AES 加密与 PHP 不同

java - 在 pdf-renderer (java) 上设置页边距

c++ - 检查所有 __m128i 组件是否为 0 的最有效方法 [使用 <= SSE4.1 内在函数]

java - 使用 Wicket 制作站点模板和主题的首选方法是什么?

java - 为什么初始容量对于从 ArrayList 中删除很重要?

Java从ArrayList中删除整数的正确方法

java - Java中如何将int[]转换为List<Integer>?

java - 当我尝试打印 vector 元素时,我得到这些奇怪的字符!

java - 如何使输入在一行上读出多个整数?

python - 如何拆分整数并将部分分配给变量