我编写了这段代码,我想知道为什么被引用的对象的值没有被更改
java中的所有调用都是按值调用。但是当调用引用同一个对象时,为什么对象没有被更新
class Main {
public static void main(String[] args) {
Integer n = 3;
triple(n);
System.out.println("Hello world! " + n);
}
public static void triple(Integer x)
{
x *= 8;
System.out.println("Hello world! " + x);
}
}
实际输出
Hello world! 24
Hello world! 3
但我认为输出应该是
Hello world! 24
Hello world! 24
是否是因为 Integer 类的拆箱和自动装箱,创建了一个与“x”同名的新对象,因为 Integer 是不可变的,在本地可用并且不指向参数/对象正在通过 - n。
最佳答案
当您将 Integer n
传递给 triple
方法时,您实际上是在传递 Integer
对象的引用值 n
.
因此,在 triple
方法中,另一个局部变量 x
在被调用时指向 this 引用值。在方法内部,当将此 Integer 对象的值与 8
相乘时,它将创建 Integer
的另一个 new 实例作为 Integer
是不可变的,局部变量x
将指向它。
因此,您不会在打印语句 System.out.println("Hello world! "+ n);
中看到这个新值,因为 n
仍然指向到 Integer 的旧实例,它仍然是 3
。
如果您使用 StringBuilder
尝试此操作,您将得到您期望的结果:
public static void main(String[] args) {
StringBuilder n = new StringBuilder("foo");
triple(n);
System.out.println("Hello world! " + n);
}
public static void triple(StringBuilder s) {
s.append("bar");
System.out.println("Hello world! " + s);
}
这里的输出将是:
Hello world! foobar
Hello world! foobar
这是因为 StringBuilder
是可变的,如果 triple
通过附加到数据来修改数据,则原始指针 n
和新指针 s
将指向对象引用的相同值。
关于java - 为什么对象没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55369951/