I have an array for example:
String [][] test = {{"a","1"},
{"b","1"},
{"c","1"}};
有人能告诉我如何从数组中删除一个元素吗?例如,我想删除项目“b”,使得数组看起来像这样:
{{"a","1"},
{"c","1"}}
我找不到方法来实现它。迄今为止我在这里发现的并不适用于我 :(
Java数组中的元素是不可删除的。在分配数组时,数组的大小已经确定,不能更改。您能做的最好的办法是:
将数组在相关位置赋值为null
;例如:
test[1] = null;
这会让你面临一个问题,即如何处理数组中null
值所在的“空洞”。(在某些情况下,这不是问题... 但在大多数情况下,它是问题。)
创建一个删除了该元素的新数组;例如:
String[][] tmp = new String[test.length - 1][];
int j = 0;
for (int i = 0; i < test.length; i++) {
if (i != indexOfItemToRemove) {
tmp[j++] = test[i];
}
}
test = tmp;
Apache Commons的ArrayUtils
类有一些静态方法可以更加简洁地实现此操作(例如Object[] ArrayUtils.remove(Object[], int)
),但事实上,这种方法仍然会创建一个新的数组对象。
更好的方法是使用合适的Collection
类型。例如,ArrayList
类型有一个方法可以删除给定位置的元素。
你可以将数组中的元素设置为null
(test[0][1] = null;
)。然而,如果要"移除"该项以使数组比之前少一个元素,则需要重新创建数组。如果你计划经常更改数据结构中的数据,则使用ArrayList
(或另一种适合你需求的集合类)可能更方便。
No need assign null to the array at the relevant position; e.g.
test[1] = null;
Create a new array with the element removed; e.g.
String[][] temp = new String[test.length - 1][];
需要获取字符串/数组中的索引以进行删除:IndexToRemove
for (int i = 0; i < test.length-1; i++) {
if (i<IndexToRemove){
temp[i]=test[i];
}else if (i==IndexToRemove){
temp[i]=test[i+1];
}else {
temp[i]=test[i+1];
}
}
test = temp;
希望它有所帮助!
ArrayList
而不是数组。 - Behrang