【问题标题】:Java static method parametersJava 静态方法参数
【发布时间】:2011-02-13 10:31:55
【问题描述】:

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

【问题讨论】:

标签: java static parameters pass-by-reference pass-by-value


【解决方案1】:

它完全按照你告诉它做的事情:-)

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 的第一个Hotel 对象。

【讨论】:

    【解决方案2】:

    它做得很好。在static Hotel doStuff(Hotel hotel) 内部,您正在创建Hotelnew 实例,旧的hotel 引用保持不变。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            猜你喜欢
            • 2018-10-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-09-22
            • 2013-12-31
            • 2016-01-21
            • 1970-01-01
            相关资源
            最近更新 更多