2 回答

TA貢獻1824條經驗 獲得超6個贊
您的問題是您正在將一個實例視為Matrix
一個數組;它不是。它有一個數組。如果您想操作newArray
實例的內部數組(我強烈建議將該變量重命名為newMatrix
),那么您可以通過訪問newArray.array
.

TA貢獻1765條經驗 獲得超5個贊
如果我在這里得到你就是你想要的:
public class Matrix {
private final int[][] array;
private final int size1;
private final int size2;
Matrix(int size1, int size2) {
this.size1 = size1;
this.size2 = size2;
this.array = new int[size1][size2];
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int[] arr: array)
builder.append(Arrays.toString(arr) + "\n");
return "Matrix{" +
"array=\n" + builder +
'}';
}
Matrix(int[][] color) {
this.size1 = color.length;
this.size2 = color[0].length;
this.array = new int[size1][size2];
for (int row = 0; row < size1; row++) {
for (int column = 0; column < size2; column++) {
this.array[row][column] = color[row][column];
}
}
}
public Matrix flipVertically() {
int start = 0, end = size1 - 1;
while (start < end) {
int[] tmp = array[start];
array[start] = array[end];
array[end] = tmp;
start++;
end--;
}
return this;
}
public static void main(String[] args) {
Matrix matrix = new Matrix(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}});
System.out.println(matrix.flipVertically());
matrix = new Matrix(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}});
System.out.println(matrix.flipVertically());
matrix = new Matrix(new int[][]{{1}});
System.out.println(matrix.flipVertically());
matrix = new Matrix(new int[][]{{1},{2},{3}});
System.out.println(matrix.flipVertically());
}
輸出:
Matrix{array=
[7, 8, 9]
[4, 5, 6]
[1, 2, 3]
}
Matrix{array=
[10, 11, 12]
[7, 8, 9]
[4, 5, 6]
[1, 2, 3]
}
Matrix{array=
[1]
}
Matrix{array=
[3]
[2]
[1]
}
要回答您的問題:
如上所述,您正在創建 Matrix 類的新實例,而不是數組。此外,這
newArray[row][column]=array[size1][size2];
不是您在 java 中復制數組的方式,盡管我認為您根本不需要復制它 - 請參閱我的實現。無論如何,如果要復制您的數組,請參閱此 在 java 中復制 2d 數組您可以這樣創建矩陣類型的變量:
Matrix matrix = new Matrix(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}});
. 在我的代碼中,我只是返回this
witch 是對自身的引用。
PS 改進代碼的建議:添加 getter 和 setter,如果沒有理由保留構造函數,則將其公開friendly
,當您將空數組傳遞給構造函數時檢查是否存在極端情況......
添加回答
舉報