Remove Items
Completed
Read n integers into an ArrayList<Integer> and remove every even number using an Iterator. Print the remaining list.
Input
n, then n integers.
Output
The list.
Example
Input
6 1 2 3 4 5 6
Output
[1, 3, 5]
Editor
Java
Hints
Removing inside a for-each loop throws ConcurrentModificationException.
it.remove() deletes the last item returned by next().
Solution explanation
The iterator knows where it is, so it can remove safely while looping.
Show solution
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
nums.add(sc.nextInt());
}
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove();
}
}
System.out.println(nums);
}
}