为什么以下代码返回 100 100 1 1 1
而不是 100 1 1 1 1
?
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() + " ");
}
}
为什么它似乎将 Hotel 按值传递给 doStuff() ?
最佳答案
它完全按照您的指示去做:-)
Hotel h1 = new Hotel(100);
System.out.print(h1.getRoomNr() + " "); // 100
Hotel h2 = doStuff(h1);
System.out.print(h1.getRoomNr() + " "); // 100 - h1 is not changed, h2 is a distinct new object
System.out.print(h2.getRoomNr() + " "); // 1
h1 = doStuff(h2);
System.out.print(h1.getRoomNr() + " "); // 1 - h1 is now changed, h2 not
System.out.print(h2.getRoomNr() + " "); // 1
正如其他人指出的(并且解释得非常清楚 in this article ),Java 按值传递。在这种情况下,它将引用 h1
的副本传递给 doStuff
。副本被新引用覆盖(然后返回并分配给 h2
),但 h1
的原始值不受影响:它仍然引用第一个酒店房间号为 100 的对象。
关于Java静态方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2731119/