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 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类维护值之间的内部缓存中的基准比较将产生正确的结果-128来127(见也TheLostMind注释).这就是我1000在我的例子中使用的原因以及为什么我特别询问拆箱/装箱而不是比较的结果.