我创建了一个矩阵/二维数组:
int [][] matrix;
看起来像这样:
0010111100
1011110111
0100101101
0101010001
0000010011
0010110101
0101101001
1010010110
0111010001
0101011101
如何添加此列:
0
0
0
0
1
0
0
0
0
0
在给定索引处,不删除最后一列?矩阵将有 11 列,而不是 10 列。
最佳答案
简单的解决方案:创建一个新的二维数组,其中多一列,并将所有值复制到新数组。 下面我展示了我所讨论内容的一个简单实现。 我省略了任何类型的检查。另外,我假设所有行都具有相同的列数。
public static int[][] addColumn(int[][] matrix, int[] column, int index) {
int[][] result = new int[matrix.length][matrix[0].length + 1];
for (int r = 0; r < matrix.length; ++r) {
System.arraycopy(matrix[r], 0, result[r], 0, index);
result[r][index] = column[r];
System.arraycopy(matrix[r], index, result[r], index + 1, matrix[0].length - index);
}
return result;
}
如果您只添加列和行是固定的,那么最好有一个 int 数组列表,其中每个元素都是矩阵的一列。然后,在给定位置添加列会更容易、更高效,因为您不必复制整个矩阵。我还建议将其包装在一个类中并提供有用的方法(如需要的话,例如 getters/setters)。
关于java - 在二维数组中的特定索引处添加列而不删除任何其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31993685/