Java静态方法参数
为什么以下代码返回 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() ?
Why does the following code return 100 100 1 1 1
and not 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() + " ");
}
}
Why does it appear to pass Hotel by-value to doStuff() ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它完全按照您告诉它的方式执行:-)
正如其他人指出的那样(并且在本文中解释得很清楚 ),Java 按值传递。在本例中,它将引用
h1
的副本传递给doStuff
。在那里,副本被新引用覆盖(然后返回并分配给h2
),但h1
的原始值不受影响:它仍然引用第一个 Hotel房间号为 100 的对象。It does exactly what you told it to do :-)
As others noted (and is explained very clearly in this article), Java passes by value. In this case, it passes a copy of the reference
h1
todoStuff
. There the copy gets overwritten with a new reference (which is then returned and assigned toh2
), but the original value ofh1
is not affected: it still references the first Hotel object with a room number of 100.对 Hotel 的引用按值传递。
Reference to Hotel is passed by value.
因为 Java确实按值传递。仅在这种情况下,该值是对
Hotel
对象的引用。或者更清楚地说,Java 传递了对 h1 指向的同一对象的引用。因此,h1本身没有被修改。Because Java does pass by value. Only in this case, the value is a reference to a
Hotel
object. Or to be more clear, Java passes a reference to the same Object that h1 points to. Therefore, h1 itself is not modified.酒店引用按值传递。您仅更改了
doStuff
方法中的本地hotel
变量并返回它,而不更改原始的h1
。如果您有 setRoomNr 方法并调用hotel.setRoomNr(1)
,您可以在方法内更改原始h1
...The Hotel reference is passed by value. You're only changing the local
hotel
variable in thedoStuff
method and returning it, not changing the originalh1
. You could change the originalh1
from within the method if you had a setRoomNr method and calledhotel.setRoomNr(1)
though...它做得很好。在
static Hotel doStuff(Hotel hotel)
内,您正在创建Hotel
的new
实例,旧hotel
引用是不变的。It is doing fine. Inside
static Hotel doStuff(Hotel hotel)
, you are creating anew
instance of ofHotel
, oldhotel
reference is unchanged.