java - 整数 == int 在 java 中允许

标签 java int equals

我想知道在与 int 进行比较时,java 是否会自动将 Integer 转换为 int?或者 == 会尝试比较基元上的引用吗?

这总是正确的还是我需要做 i.intValue()==2

Integer i = Integer.valueOf(2);
if (i==2){
//always?
}

最佳答案

是的,比较int时使用 ==如有必要,参数将被拆箱。

来自 Java Language Specification 的相关部分:

15.21.1 Numerical Equality Operators == and !=

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). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

同样适用于 < , <= , > , >=等,以及+ , - , *等等。

所以,

System.out.println(Integer.valueOf(17) == 17);

打印 true :-)

but you can compare two equal strings with == and sometimes get true or fals depending on how the strings were pooled...

对了,其实Integers也有类似的情况

当装箱(将 int 转换为 Integer )时,编译器对较小的值 (-128 - 127) 使用缓存并为相同的值重用相同的对象,所以可能有点令人惊讶,我们有以下内容:

System.out.println(Integer.valueOf(100) == Integer.valueOf(100)); // prints true
System.out.println(Integer.valueOf(200) == Integer.valueOf(200)); // prints false

关于java - 整数 == int 在 java 中允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7672317/

相关文章:

c++ - cin.fail()的错误处理问题

c# - 比较两个 List<T> 对象是否相等,忽略顺序

java - 如何在 HashMap/HashSet 中存储两个相等的字符串或任何对象(具有不同的引用)?

java - 简单的非阻塞服务器

java - SWIG 更改函数签名

java - 从 jTable 获取单个 INT 值

java - 获取 equals 函数中使用的所有实例字段的名称

java - "The type java.sql.Connection is not accessible"Eclipse IDE错误

java - 检查字符 `' a '` is separated from ` 'b'` 三个位置是否

python - 仅反转列表中的整数,无需切片或反向()