Java静态方法参数

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

为什么以下代码返回 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/

相关文章:

java - 有没有办法在java中线程化方法,而不是整个类?

JDK 1.8.0_161 中的 Java Mission Control 在 Mac OS X 上启动时卡住

java - 每个模式的 DB2 事务隔离

c# - 如何在没有类名的情况下引用全局静态字典?

performance - 检测 SURF 特征 - 对性能感到失望

java - 当赋值运算符的优先级最低时,y=x++ 和 y=x-- 有何不同?

c++ - 来自另一个类的 switch 语句中的 static const int 导致错误 C2051 : case expression not constant

c++ - 非静态常量数据成员有什么意义?

Python计算器编程错误

c++ - 将模板类作为参数传递