2010-04-28 94 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引用是不變的。