ExampleDifficulty: Advanced1 min

Bounded Wildcards Example: Copying Between Lists With a Bound on Each Side

Three calls the bounded copy method accepts and an exact-type version would refuse.

A method that reads from a List<? extends Invoice> and writes into a List<? super Invoice> accepts lists of subtypes on one side and supertypes on the other. The method is void copy(List<? extends Invoice> from, List<? super Invoice> into), where ? extends Invoice means "a list of Invoice or any subtype" and ? super Invoice means "a list of Invoice or any supertype". In use:

java
List<OverdueInvoice> overdue = loadOverdue();
List<Invoice> allInvoices = new ArrayList<>();
List<Object> audit = new ArrayList<>();

copy(overdue, allInvoices);
copy(overdue, audit);
copy(allInvoices, audit);

overdue is a list of a subtype, and ? extends Invoice accepts it. audit is a list of a supertype, and ? super Invoice accepts it. Written as copy(List<Invoice>, List<Invoice>), every one of those three calls fails to compile.

What the method body may not do matters as much. It cannot add to from, and cannot read anything more specific than Object from into; it does not need to, because copying only ever reads one list and writes the other.