下面這段程序,為什麼再次輸出a的值的時候,已經變成了c的值了?有點詭異
public class Test {
public final int TYPE_ADD = 1;
/**
* 矩陣類,實現n階矩陣的加、乘、轉置運算
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] a = { { 1, 2 }, { 2, 3 } };
int[][] b = { { 4, 5 }, { 6, 7 } };
Test m = new Test();
System.out.println("輸出原始矩陣a:");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
System.out.println("兩矩陣相加:");
int[][] r = m.matrix_add(a, b);
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < r[i].length; j++) {
System.out.print(r[i][j] + "\t");
}
System.out.println();
}
System.out.println("再次輸出原始矩陣a:");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
// 矩陣相加
public int[][] matrix_add(int[][] a, int[][] b) {
int[][] c = a;
if (inputLegal(a, b, TYPE_ADD)) {// 只有同型矩陣才能相加
for (int i = 0; i < a.length; i++) {// i控制行
for (int j = 0; j < a[i].length; j++) {// j控制列
c[i][j] = a[i][j] + b[i][j];
}
}
}
return c;
}
// 矩陣類型校驗
public boolean inputLegal(int[][] a, int[][] b, int type) {
boolean flag = true;
if (type == TYPE_ADD) {
if (a.length != b.length || a[0].length != b[0].length) {
flag = false;// 判斷是否為同型矩陣
}
}
return flag;
}
}
matrix_add中有這句話不行int[][] c = a
這樣c就指向了a,他倆是同一個內容,數組是引用類型,修改c就是在修改a