gpt4 book ai didi

java - scjp 传递对象

转载 作者:行者123 更新时间:2023-12-02 08:11:10 27 4
gpt4 key购买 nike

public class Hotel {
private int roomNr;

public Hotel(int roomNr) {
this.roomNr = roomNr;
}

public int getRoomNr() {
return this.roomNr;
}

static Hotel doStuff(Hotel hotel) {
hotel = new Hotel(1);
return hotel;
}

public static void main(String args[]) {
Hotel h1 = new Hotel(100);
System.out.print(h1.getRoomNr() + " ");
Hotel h2 = doStuff(h1);
System.out.print(h1.getRoomNr() + " ");
System.out.print(h2.getRoomNr() + " ");
h1 = doStuff(h2);
System.out.print(h1.getRoomNr() + " ");
System.out.print(h2.getRoomNr() + " ");
}
}

为什么调用 doStuff(h1) 后 h1 没有改变?据我了解,应该传递对对象的引用,并且在方法中应该将其替换为新对象。

最佳答案

在这一部分

static Hotel doStuff(Hotel hotel) {
hotel = new Hotel(1);
return hotel;
}

变量hotel是一个新的局部变量,接收引用值。这个新的局部变量在第一行加载了对新 Hotel 实例的新引用,并返回了这个新引用

外部局部变量h1不会改变。

<小时/>
main:h1 = 0x0000100                     (the old Hotel's address)
|
copying
|
-------> doStuff:hotel = 0x0000100 (the method call)
doStuff:hotel = 0x0000200 (the new Hotel's address)
|
copying
|
main:h2 = 0x0000200 <---------

关于java - scjp 传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7401825/

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