Autoboxing Trap
Completed
Read n integers into a List<Integer> and a value x. Call list.remove(Integer.valueOf(x)) to remove the value x (first occurrence), then list.remove(0) to remove the item at index 0. Print the list after each step.
Input
n, the integers, then x.
Output
Two lines.
Example
Input
5 10 20 30 20 40 20
Output
[10, 30, 20, 40] [30, 20, 40]
Editor
Java
Hints
remove(int) removes by index; remove(Object) removes by value.
Integer.valueOf(x) makes it an object.
Solution explanation
Autoboxing converts between int and Integer automatically - which makes this overload easy to get wrong.
Show solution
import java.util.ArrayList;
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> list = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
list.add(sc.nextInt());
}
int x = sc.nextInt();
list.remove(Integer.valueOf(x));
System.out.println(list);
list.remove(0);
System.out.println(list);
}
}