按引用与按值传递的示例

二、数据作为方法参数示例代码:

// PassArray.java

// Passing arrays and individual array elements to methods

public class PassArray {

public static void main(String[] args) {

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

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

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

output += "   " + a[i];//输出原始数组的值

output += " Effects of passing array " + "element call-by-value: "

+ "a[3] before modifyElement: " + a[3];//输出a[3]的原始数据

modifyElement(a[3]);//定义一个方法,引用传递

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

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

       //按值传送数组类型方法参数

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

 

output += " The values of the modified array are: ";

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]的值,最后输出的就是更改后的的值;后者的方法体修改的仅是原始数组数组元素的一个拷贝。

  按引用传递与按值传送数组类型方法参数的最大关键在于:

使用前者时,如果方法中有代码更改了数组元素的值,实际上是直接修改了原始的数组元素。

使用后者则没有这个问题,方法体中修改的仅是原始数组元素的一个拷贝。

原文地址:https://www.cnblogs.com/1995-qxl/p/4922975.html