公共类ArrayApp { 公共静态无效主(字符串[]参数){
int [] [] numbers = new int [2] [4]; // row and column
numbers [0] [0] = 1;
numbers [0] [1] = 2;
numbers [0] [2] = 3;
numbers [0] [3] = 4;
numbers [1] [0] = 5;
numbers [1] [1] = 6;
numbers [1] [2] = 7;
numbers [1] [3] = 8;
int row = 0, column = 0;
// delete item
int deleteKey = 4;
for(row = 0; row < numbers.length; row++){
for (column = 0; column < numbers[row].length; column++){
if(numbers[row][column] == deleteKey){
// this is where I want to move the array to eliminate the item with key "4"
for (int traverse = numbers[row][column]; traverse < numbers.length-1; traverse++){
numbers[row][column] = numbers[row+1][column+1];
}
break;
} // end if
}
} // end for
} // end main
} // 课程结束
我想使用某种数组遍历来删除键为“4”的项目,但我的代码不会删除它。我将不胜感激任何帮助,谢谢。
简短回答:
您的代码与循环有一个流程,这是更新的遍历代码:
boolean found = false;
for (; row < numbers.length; row++) {
for (; column < numbers[row].length; column++) {
if (numbers[row][column] == deleteKey) {
found = true;
// Shift elements one step left starting from the deleted element's index
for (int traverse = column; traverse < numbers[row].length - 1; traverse++) {
numbers[row][traverse] = numbers[row][traverse + 1];
}
break; // Exit inner loop after finding the element
}
}
if (found) {
break; // Exit outer loop after finding and shifting elements
}
}
说明:
你不能
您无法从数组中“删除项目”。如果我正确理解您的代码,您将把每个项目向下移动一步并将最后一个元素设置为 null。但是,这并不是删除,
numbers.length
仍会返回相同的属性。
您可以尝试以下几件事:
ArrayList<ArrayList<Integer>> numbers = new ArrayList<>();
numbers.add(new ArrayList<>());
numbers.get(0).add(10);
numbers.get(0).add(20);
numbers.get(0).add(30);
// Remove the item at row 0, column 1 (index 1 of the inner list)
numbers.get(0).remove(1);
null
代表已删除的值,并在程序中添加条件以跳过 null
值最后,不可能从数组中“删除”某些内容(阅读 DSA 以进一步了解它),并且在使用数组时只有解决方法。