2010-04-28 95 views
3

为什么下面的代码返回100 100 1 1 1而不是100 1 1 1 1Java静态方法参数

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()?

+3

http://stackoverflow.com/questions/40480/is-java-pass-by-reference – polygenelubricants 2010-04-28 16:01:12

+3

Java传递值。看到链接的问题。 (另外,'static'与它无关)。 – polygenelubricants 2010-04-28 16:02:18

回答

10

这不正是你告诉它做:-)

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对象。

4

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

5

对酒店的引用是通过价值传递的。

1

The Hotel引用是按值传递的。您只更改doStuff方法中的当地hotel变量并将其返回,而不更改原始h1。您可以h1从更改方法中,如果你有一个setRoomNr方法,并呼吁hotel.setRoomNr(1)虽然...

1

它做得很好。在static Hotel doStuff(Hotel hotel)里面,你正在创建一个new的实例,其中的Hotel,旧的hotel引用是不变的。