java 迭代时从 ArrayList 中删除奇数元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15674960/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:27:53  来源:igfitidea点击:

Remove odd elements from ArrayList while iterating

java

提问by Rishad Bharucha

I have an ArrayList of Strings and I'm trying to remove the odd elements of the ArrayList, i.e. list.remove(1), list.remove(3), list.remove(5) etc.

我有一个字符串 ArrayList,我正在尝试删除 ArrayList 的奇数元素,即 list.remove(1)、list.remove(3)、list.remove(5) 等。

This is the code I'm attempting to use which throws up an IllegalStateException error:

这是我尝试使用的代码,它会引发 IllegalStateException 错误:

int i = 0;
    for (Iterator<String> it = words.iterator(); it.hasNext(); )
    {
        if (i % 2 != 0 && it.hasNext())
        {
            it.remove();
        }
        i++;
    }

Is there a better (working) way to do this?

有没有更好的(工作)方法来做到这一点?

回答by prasanth

int i = 0;
    for (Iterator<String> it = words.iterator(); it.hasNext(); )
    {
        it.next(); // Add this line in your code
        if (i % 2 != 0)
        {
            it.remove();
        }
        i++;
    }

回答by Daniel Imms

You can try something like this to remove every second element starting from words[1]. No need to check whether the index is odd, when we remove an element we can just increment iand that will be the next odd number.

您可以尝试这样的操作来删除从words[1]. 无需检查索引是否为奇数,当我们删除一个元素时,我们只需递增i,这将是下一个奇数。

int i = 1;

while (i < words.size()) {
    words.remove(i++);
}

回答by Pratik

You need to clone this Array or copy that odd element into another array. During iterate time it was used same object so if you remove its index and state was changes.

您需要克隆此数组或将该奇数元素复制到另一个数组中。在迭代期间,它使用了相同的对象,因此如果您删除它的索引并且状态会发生变化。

int i = 0;
    List<String> list = new ArrayList<String>();
    List<String> words = new ArrayList<String>();
    for (String word:words)
    {
        if (i % 2 != 0)
        {

            //it.remove();
            list.add(word);
        }

        i++;
    }
    words.removeAll(list);

now just remove this all by passing this list to your words list object

现在只需将此列表传递给您的单词列表对象即可将其全部删除

words.removeAll(list);

回答by Bohemian

I wouldn't use an iterator, because you don't need to examine the elements. Just use List.remove(index):

我不会使用迭代器,因为您不需要检查元素。只需使用List.remove(index)

for (int i = words.size() - 1; i >=0; i--) {
    if (i % 2 == 1) {
        words.remove(i);
    {
}

Note that you must count down, not up with this approach because removing an element shuffles e everything after to the left

请注意,您必须倒计时,而不是使用这种方法倒计时,因为删除元素会将 e 之后的所有内容都向左打乱

If your list is immutable (explains the exception) make a copy first:

如果您的列表是不可变的(解释异常),请先复制一份:

words = new ArrayList(words);

回答by SudoRahul

Just use this.

就用这个。

for (int i = 1; i < list.size(); i++) {
    list.remove(i);
}

回答by artfullyContrived

The below also works fine

下面也可以正常工作

public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3,
                4, 5, 6, 7, 8, 9));

        for (int i = 0; i < list.size(); i++) {
            System.out.println(i);
            list.remove(i);
        }
        System.out.println(list);
    }

yielding

屈服

[2, 4, 6, 8]

回答by Sudhanshu Umalkar

You need to use next() and then call remove() ---

您需要使用 next() 然后调用 remove() ---

    int counter = 0;
    for (final Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        iterator.next();
        if (++counter % 2 != 0) {
            iterator.remove();
        }
    }

回答by Youness Marhrani

public static List<Integer> removeImpairElements(List<Integer> integers){
int j = 0; 
for(int i = 0 ; i < integers.size(); i++){
  if( i % 2 == 0){
    integers.set(j, integers.get(i));
    j++;
  }
}
int half = integers.size()%2==0 ? integers.size()/2 : integers.size()/2 + 1;  
integers.subList(half , integers.size()).clear();
return integers;

}

}