gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:34 24 4
gpt4 key购买 nike

我想知道在与 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com