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.
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), is it happening that any even number couldn't 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?
Thanks
Use an Iterator
. It has an remove()
method which you need.
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);