java 函數參數傳遞解釋

起因:

寫android的程序時,要寫一大堆賦值

txtYaw = (TextView)findViewById(R.id.txtYaw);
        txtPitch = (TextView)findViewById(R.id.txtPitch);
        txtRoll = (TextView)findViewById(R.id.txtRoll);

於是將 (TextView)findViewById封裝爲函數:

private void setTextViewID(TextView tv,int id)
    {
        tv = (TextView)findViewById(id);
    }

setTextViewID(RVP,R.id.RVP);

看起來更整潔,但是發現在RVP.seText報錯:

 E/AndroidRuntime﹕ FATAL EXCEPTION: main  java.lang.NullPointerException

發現RVP爲null

於是惡補了以下java 函數參數,以“java 函數 參數 傳遞“爲關鍵字搜索,發現講的不清不出,還是搜了stack overflow


http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

以下爲主要內容:

Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those references are passed by value.

我的理解:java 函數 參數 傳遞對象時,函數內部可以修改對象的屬性,但是重新給對象的引用賦值不行,因爲引用本身爲傳值。

It goes like this:

public static void main( String[] args ){
    Dog aDog = new Dog("Max");
    foo(aDog);
    if( aDog.getName().equals("Max") ){ //true
        System.out.println( "Java passes by value." );
    }else if( aDog.getName().equals("Fifi") ){
        System.out.println( "Java passes by reference." );
    }
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    d = new Dog("Fifi");
    d.getName().equals("Fifi"); // true
}

In this example aDog.getName() will still return "Max". The value aDog within main is not overwritten in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.

Likewise:

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

public void foo(Dog d) {
    d.getName().equals("Max"); // true
    d.setName("Fifi");
}
再有就是傳遞數組也是同樣道理:數組內部可以修改,new一個新的數組不行
    public class ArrayPar  
    {  
        public static void main(String [] args)  
        {  
            int x=1;  
            int y[]={1,2,3};  
            changeValue(x,y);  
            System.out.println("outside changeValue x="+x+",y[0]="+y[0]);
        changeRef(y);
        System.out.println("Outside changeRef y[0]="+y[0]);  
        }  
        public static void changeValue(int num,int [] array)  
        {  
            num=100;  
            array[0]=100;  
        }  
    public static void changeRef(int [] array)  
        {  
            array = new int[3];
        array[0] = 123;
            System.out.println("inside changeRef array[0]="+array[0]);       
        }  
    }  

結果:
java ArrayPar 
outside changeValue x=1,y[0]=100
inside changeRef array[0]=123
Outside changeRef y[0]=100//不變

回到最初的問題,java缺少宏 或者 inline等 文本替換的方式
變通策略可以採用 Sting to code 的方式,不過代價比較高,得不償失





發佈了38 篇原創文章 · 獲贊 14 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章