按引用與按值傳遞的示例

2、數據做爲方法參數示例代碼:java

 

// PassArray.java數組

// Passing arrays and individual array elements to methodsspa

 

public class PassArray {blog

 

public static void main(String[] args) {element

int a[] = { 1, 2, 3, 4, 5 };class

String output = "The values of the original array are:\n";sed

 

for (int i = 0; i < a.length; i++)引用

output += "   " + a[i];//輸出原始數組的值方法

output += "\n\nEffects of passing array " + "element call-by-value:\n"im

+ "a[3] before modifyElement: " + a[3];//輸出a[3]的原始數據

 

modifyElement(a[3]);//定義一個方法,引用傳遞

output += "\na[3] after modifyElement: " + a[3];

output += "\n Effects of passing entire array by reference";

       //按值傳送數組類型方法參數

modifyArray(a); // array a passed call-by-reference

 

output += "\n\nThe values of the modified array are:\n";

 

for (int i = 0; i < a.length; i++)

output += "   " + a[i];

 

System.out.println(output);

}

 

public static void modifyArray(int b[]) {

for (int j = 0; j < b.length; j++)

b[j] *= 2;//方法的使用,改變了組數元素的值,直接修改了原始的數組元素

}

public static void modifyElement(int e) {

e *= 2;

}

 

}

運行結果:

分析:引用傳遞跟值傳遞方法的區別:

  前者是若直接在方法體改變a[3]的值,最後輸出的就是更改後的的值;後者的方法體修改的僅是原始數組數組元素的一個拷貝。

  按引用傳遞與按值傳送數組類型方法參數的最大關鍵在於:

使用前者時,若是方法中有代碼更改了數組元素的值,其實是直接修改了原始的數組元素。

使用後者則沒有這個問題,方法體中修改的僅是原始數組元素的一個拷貝。

相關文章
相關標籤/搜索