Video in progress

Why can't you write List<int>, and how does that affect performance?

Generics only work with reference types, because after compilation the type parameter becomes Object. That is why you use List<Integer>, and every int is automatically boxed into an Integer.

📖 Answer

List<Integer> nums = new ArrayList<>();
nums.add(5);            // really nums.add(Integer.valueOf(5))
int x = nums.get(0);    // really nums.get(0).intValue()

This is autoboxing. It is convenient, but not free:

  • every element is a separate object, about 16 bytes with its header, plus another reference in the list;
  • it can be null: int x = map.get("yo'q") throws an NPE during unboxing;
  • outside the -128..127 range, comparing with == gives the wrong result.

With lots of numbers, int[] or IntStream is better. For example, when computing statistics, list.stream().mapToInt(Integer::intValue).sum() leaves boxing once and then works on primitives.