gpt4 book ai didi

java - 包装器自动装箱

转载 作者:行者123 更新时间:2023-11-30 04:18:23 28 4
gpt4 key购买 nike

public class Wrap
{
public static void main(String args[])
{
Integer a =1000;
Integer b =1000;
System.out.println(a == b); //line 7
Integer c = 10;
Integer d = 10;
System.out.println(c == d); // line 10
}
}

理解部分:第7行正在比较引用变量是否引用同一个对象。第 10 行比较了包装器对象所保存的实际原始数据。

我发现:如果值在 -128 到 127 之间,它将比较原始值,否则检查引用变量是否引用同一对象

我的问题:为什么会这样?这里面有什么逻辑吗?这样的逻辑还有用吗?或者是它只是用一种神谕的方式来说明 java 与其他语言的不同之处。

最佳答案

Understood part: In line 7 it is comparing whether reference variable referring to same object or not.

正确

And in line 10 its comparing the actual primitive data that wrapper object holds.

不,它的作用完全相同。

What I found: If value is between -128 to 127 it will compare primitive value or else check whether reference variable is referring to same object

这是整数缓存的默认范围。对于其他整数类型和 boolean 值也是如此。

My question: Why is it so?

提高性能。

Is there any logic involved?

参见 Integer.valueOf(int)

Is that logic of any use?

节省垃圾。

Or is it just an oracle way to say how java is different from other languages.

也许,Sun的想法确实如此。

关于java - 包装器自动装箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766633/

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