java中允许的Integer == int [英] Integer == int allowed in java

查看:129
本文介绍了java中允许的Integer == int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering if java automatically turns a Integer into an int when comparing to an int? Or will the == try and compare references on primitives?

这是否总是正确或我需要做什么 i.intValue()== 2

Is this always true or do I need to do i.intValue()==2?

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


推荐答案

是,比较 int 如果需要,使用 == 参数将被取消装箱。

Yes, when comparing int using == arguments will be unboxed if necessary.

Java语言规范中的相关部分:


15.21.1数值等式运算符==和!=

如果等于运算符的操作数都是数字类型,或者一个是数值类型而另一个是可转换的(第5.1.8节)是数字类型,则对操作数执行二进制数字提升(第5.6.2节)。如果提升类型的操作数是int或long,则执行整数相等测试;如果提升的类型是float或double,则执行浮点相等测试。

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.

请注意二进制数字提升执行值集转换(第5.1节。 13)和拆箱转换(§5.1.8)。对浮点值进行精确比较,无论它们的代表值是从哪个值集中得出。

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.

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

Same applies for <, <=, >, >= etc, as well as +, -, * and so on.

所以,

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...

对,整数以及。

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

When boxing (transforming int to Integer) the compiler uses a cache for small values (-128 - 127) and reuses the same objects for the same values, so perhaps a bit surprising, we have the following:

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

这篇关于java中允许的Integer == int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆