gpt4 book ai didi

java - 包装器类型真的是引用类型吗

转载 作者:行者123 更新时间:2023-11-29 06:39:32 25 4
gpt4 key购买 nike

看这段代码

 Integer x=new Integer(55);
Integer y=x;
y=33;
System.out.println(x);//x still prints 55 instead of 33

为什么 x 打印 55

我认为 x 应该打印 33 因为它是引用类型..这可能很愚蠢但是我是 java

的新手

最佳答案

y = x 之后,xy 都指向同一个包含值 55 的 Integer 对象。

但是这一行:

y = 33;

做了两件事:它自动创建一个值为 33 的 Integer 对象(自动装箱)并使变量 y 指向该新对象。此时,变量 x 仍指向原始 Integer (55)。

注意:这与原语无关:

StringBuilder x = new StringBuilder("abc");
StringBuilder y = x; //y's value is "abc"
y = new StringBuilder("def"); //y's new value is "def", but x's value still is "abc"

关于java - 包装器类型真的是引用类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14185432/

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