在java中,不允許程序員選擇值傳遞還是地址傳遞各個參數,基本類型總是按值傳遞。對於對象來說,是將對象的引用也就是副本傳遞給了方法,在方法中只有對對象進行修改才能影響該對象的值,操作對象的引用時是無法影響對象。
現在說說數組:如果將單個基本類型數組的元素傳遞給方法,並在方法中對 其進行修改,則在被調用方法結束執行時,該元素中存儲的並不是修改后的值,因為這種元素是按值傳遞,如果傳遞的是數組的引用,則對數組元素的后續修改可以 在原始數組中反映出來(因為數組本身就是個對象,int[] a = new int[2];,這里面的int是數組元素的類型,而數組元素的修改是操作對象)。
public class Test{ String str = new String("good"); char[] ch = {'a','b','c'}; int i = 10; public void change(String str,char[] ch,int i){ str = "test ok"; ch[0] = 'g'; i++; } public static void main(String[] args){ Test tt = new Test(); tt.change(tt.str,tt.ch,tt.i); System.out.println(tt.i); System.out.print(tt.str+" and "); System.out.println(tt.ch); }
tr是String類型的引用,i是基本類型變量,ch是數組名,也是數組對象的引用
在chang()方法里,str="test ok",是一個新的對象把首地址放在引用變量str上;
而ch[0]='g';因為傳的是數組的引用,而此時ch[0]='g';是對數組元素的操作,能修改源數組的內容;
i是整型值,只是把值copy了一份給方法,在方法的變化是不改變的源i的。
所以結果是:
10
good and gbc
public class Test{ String str = new String("good"); char[] ch = {'a','b','c'}; int i = 10; public void change(String str,char ch,int i){ str = "test ok"; ch = 'g'; this.i = i+1; } public static void main(String[] args){ Test tt = new Test(); tt.change(tt.str,tt.ch[0],tt.i); System.out.println(tt.i); System.out.print(tt.str+" and "); System.out.println(tt.ch); } }
仔細觀察下實參以及入參有何變化?
change()方法里的入參char[] ch變成--------------char ch;
這次傳遞的是個char值的單個數組元素,按照上面的解析,此時ch='9';是不影響源數組元素的。
this.i = i+1;這里面等號左邊的i是屬性i,等號右邊的i是局部變量(入參里的i);
此時i+1后賦值給屬性的i,自然會改變屬性i的值,同時17行,tt.i又是調用屬性的i,這次的結果是:
11
good and abc
http://blog.csdn.net/niuniu20008/article/details/2953785