3

为什么下面的代码返回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() ?

4

5 回答 5

10

它完全按照您的要求执行:-)

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

正如其他人所指出的(并且在本文中进行了非常清楚的解释),Java 按值传递。h1在这种情况下,它传递对 的引用的副本doStuff。在那里,副本被新的引用覆盖(然后返回并分配给h2),但 的原始值h1不受影响:它仍然引用房间号为 100 的第一个 Hotel 对象。

于 2010-04-28T16:02:33.067 回答
5

对 Hotel 的引用是按值传递的。

于 2010-04-28T16:01:14.547 回答
4

因为Java确实按值传递。只有在这种情况下,值才是对Hotel对象的引用。或者更清楚地说,Java 传递了对 h1 指向的同一个 Object 的引用。因此,h1 本身没有被修改。

于 2010-04-28T16:00:51.073 回答
1

Hotel 引用按值传递。您只是更改方法hotel中的局部变量doStuff并返回它,而不是更改原始的h1. 如果您有一个 setRoomNr 方法并被调用,您可以h1从该方法中更改原始文件hotel.setRoomNr(1)...

于 2010-04-28T16:03:44.650 回答
1

它做得很好。在里面static Hotel doStuff(Hotel hotel),你正在创建一个newof 的实例Hotel,旧的hotel引用没有改变。

于 2010-04-28T16:08:44.937 回答