PECS: copy and sort with a supertype comparator
A wildcard ? stands for "some type I don't name". List<? extends Number> is a list you can safely read Numbers from, and List<? super Integer> is one you can safely add Integers to. PECS, "Producer Extends, Consumer Super", tells you which to use.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static double average(Collection<? extends Number> values) and test it with a List<Integer> and a Set<Double> (use TreeSet).
Write static void addRange(List<? super Integer> out, int from, int to) and use it to fill both a List<Integer> and a List<Object> that already contains "start".
Write static <T> void moveAll(List<? extends T> from, List<? super T> to) that copies all elements and prints the count moved. Move List.of(1.5, 2.5) into a List<Number>.
Explain it without notes
What problem do wildcards solve? Explain with List<Integer> and List<Number>.
Explain PECS with Collections.copy as the example.
Why can't you add to a List<? extends Number>, and why can you only read Object from a List<? super Integer>?
What is the difference between List<?>, List<Object> and raw List?
What is wildcard capture, and how does a capture helper work?
Expected output
[1, 2, 3] [1, 2, 3, x]
heaviest: kesar
sorted: [alphonso, langra, kesar]