1. 程式人生 > >總結java方法(函式)傳值和傳引用的問題

總結java方法(函式)傳值和傳引用的問題

java方法中傳值和傳引用的問題是個基本問題,但是也有很多人一時弄不清。

(一)基本資料型別:傳值,方法不會改變實參的值。

public class TestFun {

public static void testInt(int i){
   i=5;   


public static void main(String[] args) {
   int a=0 ;  
   TestFun.testInt(a);
   System.out.println("a="+a);  
}

}

程式執行結果:a=0 。

(二)物件型別引數:傳引用,方法體內改變形參引用,不會改變實參的引用,但有可能改變實參物件的屬性值。

舉兩個例子:

(1)方法體內改變形參引用,但不會改變實參引用 ,實參值不變。

public class TestFun2 {

public static void testStr(String str){
   str="hello";//型參指向字串 “hello”   


public static void main(String[] args) {
   String s="1" ;  
   TestFun2.testStr(s);
   System.out.println("s="+s); //實參s引用沒變,值也不變 
}
}

執行結果列印:s=1

(2)方法體內,通過引用改變了實際引數物件的內容,注意是“內容”,引用還是不變的。

import java.util.HashMap;
import java.util.Map;

public class TestFun3 {

public static void testMap(Map map){
   map.put("key2","value2");//通過引用,改變了實參的內容  


public static void main(String[] args) {
   Map map = new HashMap(); 
   map.put("key1", "value1");
   new TestFun3().testMap(map);
   System.out.println("map size:"+map.size()); //map內容變化了 
}
}

執行結果,列印:map size:2 。可見在方法testMap()內改變了實參的內容。

(3)第二個例子是拿map舉例的,還有經常涉及的是 StringBuffer :

public class TestFun4 {

public static void testStringBuffer(StringBuffer sb){
   sb.append("java");//改變了實參的內容 


public static void main(String[] args) {
   StringBuffer sb= new StringBuffer("my "); 
   new TestFun4().testStringBuffer(sb);
   System.out.println("sb="+sb.toString());//內容變化了 
}
}

執行結果,列印:sb=my java 。

所以比較引數是String和StringBuffer 的兩個例子就會理解什麼是“改變實參物件內容”了。

總結

第一:java方法基本資料型別是傳值,物件型別傳引用,這是千真萬確的。

第二:當引數是物件時,無論方法體內進行了何種操作,都不會改變實參物件的引用。

第三:當引數是物件時,只有在方法內部改變了物件的內容時,才會改變實參物件內容。