2011-08-08 44 views
4

可能重複:
Is Java pass by reference?爪哇 - 這似乎是通過引用傳遞給我

所以考慮以下兩個例子,它們各自的輸出:

public class LooksLikePassByValue { 

    public static void main(String[] args) { 

     Integer num = 1; 
     change(num); 
     System.out.println(num); 
    } 

    public static void change(Integer num) 
    { 
     num = 2; 
    } 
} 

輸出:


public class LooksLikePassByReference { 

    public static void main(String[] args) { 

     Properties properties = new Properties(); 
     properties.setProperty("url", "www.google.com"); 
     change(properties); 
     System.out.println(properties.getProperty("url")); 
    } 

    public static void change(Properties properties2) 
    { 
     properties2.setProperty("url", "www.yahoo.com"); 
    } 
} 

輸出:

www.yahoo.com

爲什麼會變成這樣www.yahoo.com?這看起來並不像passbyvalue我。

+0

另請參閱:http://stackoverflow.com/questions/40480/is-java-pass-by-reference – 2011-08-08 18:57:41

回答

10

參考是通過值。但新的參考仍然指向相同的原始對象。所以你修改它。在Integer的第一個示例中,您正在更改參考點所指向的對象。所以原來的一個沒有修改。

1

這是按值傳遞,但值是對屬性的引用,並且不會更改它,只是它的一些內部字段。

在第一種情況下,您更改引用而不是引用的任何成員,而在第二種情況下,您更改引用的成員,但保留引用的原樣。

0

這是因爲properties2只不過是一個對象引用。這意味着傳遞給該方法的引用實際上是原始引用的副本。由於這說明,

enter image description here

1

試試這個:

public class LooksLikePassByReference { 

    public static void main(String[] args) { 

     Properties properties = new Properties(); 
     properties.setProperty("url", "www.google.com"); 
     change(properties); 
     System.out.println(properties.getProperty("url")); 
    } 

    public static void change(Properties properties2) 
    { 
     properties2 = new Properties(); 
     properties2.setProperty("url", "www.yahoo.com"); 
    } 
} 

它打印出 「www.google.com」。

您實際上正在傳遞參考文獻的值,因此可以看到通過該參考對對象所做的更改。但是,如果您爲參數指定了新的對象引用,那麼該更改將反映而不是,因爲您只通過參考值,而不是實際參考變量。

2

你的第一個例子做:

num = 2 

這是一樣的

num = new Integer(2) 

所以你看它是如何是不太一樣的你的第二個例子。如果整數讓你設置它的值,你可以這樣做:

num.setValue(2) // I know Integer doesn't allow this, but imagine it did. 

這將完成第二個例子。