本文介绍了从 ArrayList 中删除偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的代码:

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);

 }

代码的输出为:

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

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

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.

谢谢

推荐答案

使用 迭代器.它有一个您需要的 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);

这篇关于从 ArrayList 中删除偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 22:18