问题描述
我有一个数组,例如:
String [][] test = {{"a","1"},
{"b","1"},
{"c","1"}};
谁能告诉我如何从数组中删除一个元素.例如我想删除项目b",使数组看起来像:
Can anyone tell me how to remove an element from the array. For example I want to remove item "b", so that the array looks like:
{{"a","1"},
{"c","1"}}
我找不到这样做的方法.到目前为止我在这里找到的东西对我不起作用:(
I can't find a way of doing it. What I have found here so far is not working for me :(
推荐答案
不能从数组中删除元素.Java 数组的大小是在分配数组时确定的,不能更改.你能做的最好的是:
You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:
将
null
赋给相关位置的数组;例如
Assign
null
to the array at the relevant position; e.g.
test[1] = null;
这给您留下了处理数组中 null
值所在的漏洞"的问题.(在某些情况下这不是问题……但在大多数情况下是.)
This leaves you with the problem of dealing with the "holes" in the array where the null
values are. (In some cases this is not a problem ... but in most cases it is.)
创建一个删除元素的新数组;例如
Create a new array with the element removed; e.g.
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)
,但事实仍然是这种方法创建了一个新的数组对象.
The Apache Commons ArrayUtils
class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int)
, but the fact remains that this approach creates a new array object.
更好的方法是使用合适的 Collection
类型.例如,ArrayList
类型有一个方法,允许您删除给定位置的元素.
A better approach would be to use a suitable Collection
type. For instance, the ArrayList
type has a method that allows you to remove the element at a given position.
这篇关于如何从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!