Generics
A list of strings is not a list of who knows what.
List<String> is a list in which the compiler expects strings. That check happens before anything runs. A raw List without a parameter lets you put anything in and fails later, at a cast. New code does not use raw types.
Generics are erased at runtime: at that point the JVM sees an ordinary list. That is why you cannot write new String[n] from a type parameter alone without tricks, and cannot ask instanceof List<String>. Check the element type at the input, while the element is still in your hands.
The method <T> T first(List<T> items) works for any list. The bound <T extends CharSequence> narrows the set. In the task, List<String> and one element are enough. An empty list gets its own answer, none, not an exception: the caller asks "is there a first element", not "crash if there is none".
List.of("go", "java") gives an immutable list. You cannot call add on it. To build a list by adding, use ArrayList. Mixing them up is a typical defect in a test that first created List.of and then decided to append an element.
Practice
Why a type parameter
What does List give you compared to a raw List?
- The list becomes ten times faster
- You cannot add a foreign type without a build error
- The list sorts itself
- String becomes a primitive
An empty list
In this task, what text means "there is no first element"?
The first element
Write static String first(List items). Return the first element, or none if the list is empty.