Command Palette

Search for a command to run...

Back to the lesson: Topic 8.5 — Wildcards and PECS
Core Java · Example 1 of 5

? extends: one sum method for every kind of number

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.

01

Write static double average(Collection<? extends Number> values) and test it with a List<Integer> and a Set<Double> (use TreeSet).

02

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".

03

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

01

What problem do wildcards solve? Explain with List<Integer> and List<Number>.

02

Explain PECS with Collections.copy as the example.

03

Why can't you add to a List<? extends Number>, and why can you only read Object from a List<? super Integer>?

04

What is the difference between List<?>, List<Object> and raw List?

05

What is wildcard capture, and how does a capture helper work?

? extends: one sum method for every kind of number
Sign in to run this example in your browser.

Expected output

ints: 6.0
doubles: 4.0
mixed: 110.5
non-null strings: 2
non-null ints: 3