数组参数
可以将数组作为参数传递给方法或构造函数。传递给该方法的数组的类型必须是与形式参数类型兼容的赋值(即,形参和实参的数组类型要一样。
以下代码显示了如何将数组作为方法参数传递 -
public class Main {
public static void main(String[] args) {
int[] num = { 1, 2 };
System.out.println("Before swap");
System.out.println("#1: " + num[0]);
System.out.println("#2: " + num[1]);
swap(num);
System.out.println("After swap");
System.out.println("#1: " + num[0]);
System.out.println("#2: " + num[1]);
}
public static void swap(int[] source) {
if (source != null && source.length == 2) {
// Swap the first and the second elements
int temp = source[0];
source[0] = source[1];
source[1] = temp;
}
}
}
Java
上面的代码生成以下结果。
Before swap
#1: 1
#2: 2
After swap
#1: 2
#2: 1
Java
数组参数引用
因为数组是一个对象,所以它的引用副本可传递给一个方法。如果方法更改数组参数,实际参数不受影响。
imp