如何从数组中删除元素 [英] How to remove element from an array
问题描述
我有,例如一个数组:
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:
-
分配
空
在相关位置上的数组;例如。
Assign
null
to the array at the relevant position; e.g.
test[1] = 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 (j != indexOfItemToRemove) {
tmp[j++] = test[i];
}
}
test = tmp;
阿帕奇共享 ArrayUtils
类有一些静态方法,将做到这更加整齐(例如<一个href=\"http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html#remove%28java.lang.Object%5B%5D,%20int%29\"相对=nofollow> 对象[] ArrayUtils.remove(对象[],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.
有一个更好的办法是使用合适的收藏
键入。例如,的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.
这篇关于如何从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!