一旦在java中创建了一个具有固定长度的数组,那么在您的情况下,在使用数组Inicializer之后,您将得到一个
长度为3的数组
,具有类型的元素
字符数组
其中每个固定长度也为3。要替换给定值,只需将新值分配给适当的索引,如:
Grid[i][j] = 'new character value';
正如我已经说过的,由于大小是固定的,所以不能向其中添加新值,除非将整个数组复制到一个大小为(长度+1)的新数组中,并将新值放置在所需的位置。简单代码演示:
private static void add(char[][] grid, int row, int column, char value) {
if (row < 0 || row > grid.length) {
throw new ArrayIndexOutOfBoundsException("No such row with index " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
if (column < 0 || column > grid[row].length) {
/*
* An array in Java is with fixed length so you should keep the index inside the size!
*/
throw new ArrayIndexOutOfBoundsException("Index " + column + " does not exists in the extended array!"); // you are trying to insert an element out of the array's bounds.
}
boolean flag = false; //indicates that the new element has been inserted.
char[] temp = new char[grid[row].length + 1];
for (int i = 0; i < temp.length; i++) {
if (i == column) {
temp[i] = value;
flag = true;
} else {
temp[i] = grid[row][i - (flag ? 1 : 0)];
}
}
grid[row] = temp; //assign the new value of the whole row to it's placeholder.
}
要从数组中删除元素,必须创建一个大小为[长度-1]的新数组,跳过要删除的元素并添加所有其他元素。然后将新的分配给矩阵中的索引。简单代码:
private static void remove(char[][] grid, int row, int column) {
if (row < 0 || row > grid.length) {
throw new ArrayIndexOutOfBoundsException("No such row with index " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
if (column < 0 || column > grid[row].length) {
throw new ArrayIndexOutOfBoundsException("No such column with index " + column + " at row " + row + " inside the matrix."); // you are trying to insert an element out of the array's bounds.
}
boolean flag = false; //indicates that the element has been removed.
char[] temp = new char[grid[row].length - 1];
for (int i = 0; i < temp.length; i++) {
if (i == column) {
flag = true;
}
temp[i] = grid[row][i + (flag ? 1 : 0)];
}
grid[row] = temp; //assign the new value of the whole row to it's placeholder.
}
如果我定义一个名为
print(char[][] grid)
然后输入用于打印的代码,我就可以进行以下测试:
add(Grid, 2, 3, '$'); //Add an element.
print(Grid);
System.out.println();
remove(Grid, 2, 0); // Remove an element.
print(Grid);
System.out.println();
Grid[0][0] = '%'; // Change an element's value.
print(Grid);
输出如下:
###
###
###$
###
###
##$
%##
###
##$