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 …
我刚刚看到类似这样的代码:
public class Scratch
{
public static void main(String[] args)
{
Integer a = 1000, b = 1000;
System.out.println(a == b);
Integer c = 100, d = 100;
System.out.println(c == d);
}
}
Run Code Online (Sandbox Code Playgroud)
运行时,这段代码将打印出来:
false
true
Run Code Online (Sandbox Code Playgroud)
我理解为什么第一个是false:因为这两个对象是单独的对象,所以==比较引用.但我无法弄清楚,为什么第二个声明会回来true?当Integer的值在一定范围内时,是否会出现一些奇怪的自动装箱规则?这里发生了什么?
可能重复:
奇怪的Java拳击
最近我看到了一个演示文稿,其中有以下Java代码示例:
Integer a = 1000, b = 1000;
System.out.println(a == b); // false
Integer c = 100, d = 100;
System.out.println(c == d); // true
Run Code Online (Sandbox Code Playgroud)
现在我有点困惑.我理解为什么在第一种情况下结果是"假" - 这是因为Integer是一个引用类型,而"a"和"b"的引用是不同的.
但为什么在第二种情况下结果是"真实的"?
我听说过一个观点,即JVM将对象的int值从-128缓存到127以进行某些优化.以这种方式,"c"和"d"的引用是相同的.
有人可以给我更多关于这种行为的信息吗?我想了解这种优化的目的.在什么情况下性能提高等等.参考这个问题的一些研究将是伟大的.
Integer integer1 = 127;
Integer integer2 = 127;
System.out.println(integer1 == integer2);//true
integer1 = 128;
integer2 = 128;
System.out.println(integer1 == integer2);//false
Run Code Online (Sandbox Code Playgroud)
我发现它返回==(如果是)在范围之内-128 - 127,为什么会有这样的规范?