相关疑难解决方法(0)

Why do == comparisons with Integer.valueOf(String) give different results for 127 and 128?

I have no idea why these lines of code return different values:

System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));
Run Code Online (Sandbox Code Playgroud)

The output is:

true
false
true
Run Code Online (Sandbox Code Playgroud)

Why does the first one return true and the second one return false? Is there something different that I don't know between 127 and 128? (Of course I know that 127 < 128.)

Also, why does the third one return true?

I have read the answer of this question, but I still didn't get …

java comparison integer

179
推荐指数
5
解决办法
2万
查看次数

当使用==表示基元和盒装值时,自动装箱完成,或者取消装箱完成

以下代码编译(使用Java 8):

Integer i1 = 1000;
int i2 = 1000;
boolean compared = (i1 == i2);
Run Code Online (Sandbox Code Playgroud)

但是它做了什么?

取消框i1:

boolean compared = (i1.intvalue() == i2);
Run Code Online (Sandbox Code Playgroud)

或盒子i2:

boolean compared = (i1 == new Integer(i2));
Run Code Online (Sandbox Code Playgroud)

那么它是按比例比较两个Integer对象(通过引用)还是两个int变量?

请注意,对于某些数字,因为Integer类维护值之间的内部缓存中的基准比较将产生正确的结果-128127(见也TheLostMind注释).这就是我1000在我的例子中使用的原因以及为什么我特别询问拆箱/装箱而不是比较的结果.

java autoboxing

53
推荐指数
3
解决办法
8314
查看次数

标签 统计

java ×2

autoboxing ×1

comparison ×1

integer ×1