Java static method parameters

Why does the following code return 100 1 1 instead of 100 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() + " ");
}
}

Why does it seem to pass hotel by value to dostuff()?

Solution

It does exactly as you ask: -)

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

As others pointed out (and explained very clearly in this article), Java passed the value In this case, it passes a copy of the reference H1 to dostuff There, the copy is overwritten by the new reference (then returned and assigned to H2), but the original value of H1 is not affected: it still references the first hotel object with room number 100

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>