整型数组的情形:
public class TestArrayINT {
static void changeT (int[] a, int[] b) {
int temp;
for(int i = 0 ; i < a.length ; i ++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
public static void main(String[] args) {
int A[] = {1,2,3,4,5};
int B[] = {0,0,0,0,0};
System.out.println(A);
System.out.println(B);
for(int i = 0 ; i <A.length ; i ++){
System.out.print(A[i] + " ");
}
System.out.println();
for(int i = 0 ; i <B.length ; i ++){
System.out.print(B[i] + " ");
}
System.out.println();
changeT(A,B);
for(int i = 0 ; i <A.length ; i ++){
System.out.print(A[i] + " ");
}
System.out.println();
for(int i = 0 ; i <B.length ; i ++){
System.out.print(B[i] + " ");
}
System.out.println(A);
System.out.println(B);
}
}
从结果看,A,B的地址并没有改变,但是却实现了数组A与数组B的值的改变;
字符串数组的情形:
public class TestArrayString {
static void changeT (String[] a, String[] b) {
String temp;
for(int i = 0 ; i < a.length ; i ++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
public static void main(String[] args) {
String A[] = {"1","2","3","4","5"};
String B[] = {"0","0","0","0","0"};
System.out.println(A);
System.out.println(B);
for(int i = 0 ; i <A.length ; i ++){
System.out.print(A[i] + " ");
}
System.out.println();
for(int i = 0 ; i <B.length ; i ++){
System.out.print(B[i] + " ");
}
System.out.println();
changeT(A,B);
for(int i = 0 ; i <A.length ; i ++){
System.out.print(A[i] + " ");
}
System.out.println();
for(int i = 0 ; i <B.length ; i ++){
System.out.print(B[i] + " ");
}
System.out.println();
System.out.println(A);
System.out.println(B);
} }
从结果看,A,B的地址并没有改变,但是却实现了数组A与数组B的值的改变;
对象数组的情形:
class person {
private String name;
public person(String name){
this.name = name;
}
public String getName() {
return name;
}
}
public class TestObjuectString {
static void changeT (person[] a, person[] b) {
person temp;
for(int i = 0 ; i < a.length ; i ++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
public static void main(String[] args) {
person A[] = {new person("tom"),new person("jack"),new person("lucy"),new person("tim")};
person B[] = {new person("o1"),new person("o2"),new person("o3"),new person("o4")};
System.out.println(A);
System.out.println(B);
for(int i = 0 ; i <A.length ; i ++){
System.out.print(A[i].getName() + " ");
}
System.out.println();
for(int i = 0 ; i <B.length ; i ++){
System.out.print(B[i].getName() + " ");
}
System.out.println();
changeT(A,B);
for(int i = 0 ; i <A.length ; i ++){
System.out.print(A[i].getName() + " ");
}
System.out.println();
for(int i = 0 ; i <B.length ; i ++){
System.out.print(B[i].getName() + " ");
}
System.out.println();
System.out.println(A);
System.out.println(B);
}
}
从结果看,A,B的地址并没有改变,但是却实现了数组A与数组B的值的改变;
由此可以的得到:在数组传递的过程中是可以改变数组中各个元素的值,但是数组的地址是不变的;