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() + " ");
}
}为什么调用doStuff( h1 )后h1没有变化?据我所知,应该传递对对象的引用,并且在方法中应该将其替换为新的对象。
发布于 2011-09-13 20:33:07
在这一部分
static Hotel doStuff(Hotel hotel) {
hotel = new Hotel(1);
return hotel;
}变量hotel是一个新的局部变量,它接收参考值。这个新的局部变量在第一行加载了一个对新Hotel实例的新引用,并返回这个新引用。
外部局部变量h1不会更改。
main:h1 = 0x0000100 (the old Hotel's address)
|
copying
|
-------> doStuff:hotel = 0x0000100 (the method call)
doStuff:hotel = 0x0000200 (the new Hotel's address)
|
copying
|
main:h2 = 0x0000200 <---------发布于 2011-09-13 20:33:16
这里我要说得更具体一点:与其说引用是传递的,不如把它想象成“通过值传递的引用”。因此,基本上,该方法接收指向所考虑的对象的引用的副本。这两个引用(原始h1和新hotel)指向相同的对象,但仍然不同。在该方法中,修改的是“引用”,而不是它所引用的对象,因此也就是结果。
一个很好的读物可能是this one,其中作者使用不同语言的代码样本。
发布于 2011-09-13 20:32:32
这是因为对象是“通过值传递,而不是通过引用”。
通过值传递的是它的引用。所以,在你的眼睛里,你会认为它是通过引用传递的。
因此,为了清楚起见,当你将一个对象传递给一个方法时,一个新的“指针引用”就会被传递。所以如果你修改它,什么也不会发生。
编辑:这里有一些代码
Hotel h1 = new Hotel(100); // h1 holds a reference to a Hotel object in memory
System.out.print(h1.getRoomNr() + " ");
Hotel h2 = doStuff(h1); // when doStuff is called, a new reference pointing to the same object is made, but if you change it, nothing will happen看看Core Java吧。史上最好的书!
https://stackoverflow.com/questions/7401825
复制相似问题