Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<int> xs = new ArrayList<>();
xs.add(5);
System.out.println(xs);
}
}It does not compile
- Expecting
[5]: generics accept only reference types, soList<int>does not compile; a list of numbers isList<Integer>, and autoboxing turns5into anInteger. - Expecting an error only when the program runs: type arguments are checked by javac, so the program is rejected before it starts.
- How do you declare a list of whole numbers instead?
- What does autoboxing do when you call
xs.add(5)on aList<Integer>?