ExampleDifficulty: Advanced1 min

Copying From One List Into Another, With a Bound on Each Side

The copy method in use, and the four calls it now accepts that the unbounded version would have refused.

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 to notice is what the method body may not do. It cannot add to from and cannot read anything more specific than Object from into — and it does not need to, because copying only ever reads one and writes the other.