Java 从 ArrayList 中删除偶数

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

Remove even numbers from an ArrayList

javacollectionsarraylist

提问by Talha Bin Shakir

I have to create a method which has an ArrayList; I need to remove even numbers from this ArrayList. I have written code for that but there is a logical error which I couldn't identify.

我必须创建一个具有 ArrayList 的方法;我需要从这个 ArrayList 中删除偶数。我已经为此编写了代码,但存在一个我无法识别的逻辑错误。

Here is my code:

这是我的代码:

static void sortList(){

   List <Integer> number=new ArrayList <Integer>();

   number.add(11);
   number.add(45);
   number.add(12);
   number.add(32);
   number.add(36);

   System.out.println("Unsorted List: "+number);

   for (int i=0;i<number.size();i++){      
       int even=number.get(i)%2;       
        if (even==0){
            System.out.println("This is Even Number:"+ number.get(i));
            number.remove(i);
        }    
    }

    Collections.sort(number);
    System.out.println("Sorted List: "+number);

 }

The output of the code is:

代码的输出是:

Unsorted List: [11, 45, 12, 32, 36]
This is Even Number:12
This is Even Number:36
Sorted List: [11, 32, 45]

I am wondering that why 32 is not caught as an Even number as it is an even number, I tested then by using different even numbers at same position but the result is same. Why at index(3) its happening that any even number couldnt be catch. I am really wondering why. So please any one can help me out for this and is there any other better way to implement this solution.

我想知道为什么 32 没有被捕获为偶数,因为它是偶数,然后我通过在同一位置使用不同的偶数进行了测试,但结果是相同的。为什么在 index(3) 发生任何偶数都无法捕获的情况。我真的很想知道为什么。所以请任何人都可以帮助我解决这个问题,还有其他更好的方法来实现这个解决方案。

Thanks

谢谢

采纳答案by BalusC

Use an Iterator. It has an remove()method which you need.

使用Iterator. 它有一个remove()你需要的方法。

List<Integer> numbers = new ArrayList<Integer>();

numbers.add(11);
numbers.add(45);
numbers.add(12);
numbers.add(32);
numbers.add(36);

System.out.println("Unsorted List: " + numbers);

for (Iterator<Integer> iterator = numbers.iterator(); iterator.hasNext();) {
    Integer number = iterator.next();
    if (number % 2 == 0) {
        System.out.println("This is Even Number: " + number);
        iterator.remove();
    }

}

Collections.sort(numbers);
System.out.println("Sorted List: " + numbers);

回答by Rasmus Kaj

When you remove something from the list, the indexes of everything after that changes!

当您从列表中删除某些内容时,之后所有内容的索引都会更改!

Specifically, in your implementation 32 is not removed as it comes directly after another even number.

具体来说,在您的实现中 32 不会被删除,因为它直接出现在另一个偶数之后。

I would use an Iterator to walk over the list, and the remove operation on that iterator instead, something like this:

我会使用迭代器遍历列表,然后使用该迭代器上的删除操作,如下所示:

for(Iterator i = number.iterator(); i.hasNext(); ) {
    if (isEven(i.next()) {
        i.remove();
    }
}

回答by Adam Wright

If you remove an entry from the list whilst looping over it, you'll have to adjust your loop index. Don't forget, removing the element reduces the length of the list by one, and effectively "shuffles back" the index of all elements after it.

如果在循环时从列表中删除条目,则必须调整循环索引。不要忘记,删除元素会将列表的长度减一,并有效地“洗牌”其后所有元素的索引。

回答by Stephen

The problem (as others have mentioned) is that you are modifying the list while you are traversing it. Try adding a "i--;" line inside your "if (even==0)" block. Like this:

问题(正如其他人所提到的)是您在遍历列表时正在修改它。尝试添加一个“i--;” 在“if (even==0)”块内的行。像这样:

for (int i=0;i<number.size();i++){
    int even=number.get(i)%2;

    if (even==0){
        System.out.println("This is Even Number:"+ number.get(i));
        number.remove(i);

        // Add this:
        i--;
    }
}

回答by Walter Mundt

Both answers about list indices changing are correct. However, also be aware that removing an item from an ArrayList is slow because it has to actually shuffle all of the following entries down. Instead, I recommend creating a new list containing only the even numbers, and then just throwing away the old list. If you want to use the Iterator-based remove code in the other answer, it will work fine for small results as is, and for larger data sets if you use LinkedList. (I believe that is the name; my Java is admittedly slightly rusty.)

关于列表索引更改的两个答案都是正确的。但是,还要注意从 ArrayList 中删除项目很慢,因为它实际上必须将以下所有条目打乱。相反,我建议创建一个仅包含偶数的新列表,然后扔掉旧列表。如果您想在另一个答案中使用基于迭代器的删除代码,它可以按原样适用于较小的结果,如果使用 LinkedList,则适用于较大的数据集。(我相信这就是名字;不可否认,我的 Java 有点生疏。)

回答by dustmachine

Here's another nifty way of filtering for odd elements. Instead of looping through the collection manually, offload the work to Apache Commons Collections

这是另一种过滤奇数元素的好方法。不是手动循环遍历集合,而是将工作卸载到Apache Commons 集合

 // apply a filter to the collection
 CollectionUtils.filter(numbers, new Predicate() {
     public boolean evaluate(Object o) {
         if ((((Integer) o) % 2) == 0) { 
             return false;  // even items don't match the filter
         }
         return true;  // odd items match the filter
     }
 });

It's debatable whether this is actually easier to read and understand, but it's more fun. If a certain kind of Predicate is used frequently, it can be refactored out into a static constant and reused all over the place. This could turn the usage of it into something a lot cleaner:

这是否真的更容易阅读和理解是有争议的,但它更有趣。如果某种 Predicate 被频繁使用,它可以被重构为一个静态常量,并在所有地方重复使用。这可以将它的使用变成更干净的东西:

CollectionUtils.filter(numberList, ODD_PREDICATE);

回答by volvox

What i do (Intelliji with kotlin)

我做什么(Intelliji 与 kotlin)

fun main(args: Array<String>) {

 var numbers = arrayList(1,2,3,4,5,6)
 println(numbers.filter{it %2 == 0})

}

result=2,4,6

结果=2,4,6

回答by Sudhir Kumar

public class RemoveEvenUsingAL {

    public static void main(String[] args) {
        List<Integer> list= new ArrayList<Integer>();

        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);

        Iterator<Integer> it = list.iterator();
        while(it.hasNext()){
            Integer number= it.next();
            if(number % 2 ==0){
                it.remove();
            }
        }
        System.out.println("ArryList Odd Number="+list);
    }
}

回答by Arpit Agrawal

We can use removeIf default method in ArrayList class .

我们可以在 ArrayList 类中使用 removeIf 默认方法。

     List <Integer> number=new ArrayList <Integer>();

       number.add(11);
       number.add(45);
       number.add(12);
       number.add(32);
       number.add(36);

       number.removeIf(num -> num%2==0);

       System.out.println(number);