I was looking at the Java Generics documentation and found this piece of code,
public class WildcardError {
void foo(List> l) {
//This give a co
List>
means list containing elements of some unknown type, so when one wants to take elements from it using list.get(i)
it will return object of some unknown type, so the only valid guess will be Object
. Then when one tries to set element back using list.set(index, list.get(index))
it produces compile-time error, since as mentioned above List>
can only contain some unknown type, so putting Object
to it may cause ClassCastException
.
This is explained very well in Joshua Bloch's Effective Java, 2nd ed., Item 28: Use bounded wildcards to increase API flexibility
This is also known as PECS
principle and good explanation can be found in this Q/A:
What is PECS (Producer Extends Consumer Super)? (please note that List>
is the same as List extends Object>
with minor exceptions)
In laymans terms, one should use List>
as method parameter only to get elements from it inside that method, not when one needs to put elements into list. When one needs to both put and get he/she needs to either generify method using type parameter T
as in Lukas Eder's answer (type-safe way) or simply use List
(not type-safe way).