java 从数组中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5098540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete element from array
提问by Julio Diaz
Possible Duplicate:
Removing an element from an Array (Java)
可能的重复:
从数组中删除元素(Java)
Is there a way I can get rid of some elements in an array. for instance, if i have this array
有没有办法摆脱数组中的某些元素。例如,如果我有这个数组
int testArray[] = {0,2,0,3,0,4,5,6}
Is there a "fast" way to get rid of the elements that equal 0
有没有一种“快速”的方法来摆脱等于 0 的元素
int resultArray[] = {2,3,4,5,6}
I tried this function but I got lost using Lists
我试过这个功能,但我在使用列表时迷路了
public int[] getRidOfZero(int []s){
List<> result=new ArrayList<>();
for(int i=0; i<s.length; i++){
if(s[i]<0){
int temp = s[i];
result.add(temp);
}
}
return result.toArray(new int[]);
}
采纳答案by DJClayworth
Java arrays can't be resized. You need to create a new array.
Java 数组无法调整大小。您需要创建一个新数组。
Count the non-zero elements in the array. Create a new array that size. Copy the elements from the old to the new array, skipping over zero elements.
计算数组中的非零元素。创建一个该大小的新数组。将元素从旧数组复制到新数组,跳过零元素。
You can do this with lists. Your best bet is to create a list of Integers; add non-zero elements to it; then use toArray to create an array from the list.
你可以用列表来做到这一点。最好的办法是创建一个整数列表;向其添加非零元素;然后使用 toArray 从列表中创建一个数组。
回答by Matt Ball
You're quite close, but:
你很接近,但是:
- Your generics were messed up (
List<>
is syntactically invalid) - Your comparison was only adding the element if it was less than zero (rather than adding it if it was not equal to zero)
You were calling the wrongBecausetoArray()
method.ints
are primitives, you have to turn the list back into an array yourself.
- 你的泛型搞砸了(
List<>
在语法上无效) - 您的比较只是在元素小于零时添加元素(而不是在不等于零时添加元素)
你调用了错误的因为toArray()
方法。ints
是原语,您必须自己将列表转回数组。
public int[] getRidOfZero(int[] s) {
List<Integer> result = new ArrayList<Integer> ();
for (int i : s) {
if (i != 0) {
result.add(i);
}
}
int[] toReturn = new int[result.size()];
for (int i=0; i<result.size(); i++) {
toReturn[i] = result.get(i);
}
return toReturn;
}
回答by Matthew Willis
Since you're starting with an array, you'll need to create a new array and copy the items from the old array, excluding the zeros.
由于您从一个数组开始,您需要创建一个新数组并从旧数组中复制项目,不包括零。
If you remove a bunch of zeros at once, this is going to be fast.
如果你一次删除一堆零,这会很快。
Otherwise, you'll need to begin with the doubly-linked LinkedList.
否则,您需要从双向链接的LinkedList 开始。
LinkedList has an iterator that allows you to move along the list and remove elements, which will be a constant-time operation.
LinkedList 有一个迭代器,允许您沿列表移动并删除元素,这将是一个恒定时间的操作。