public static void main(String[] args) { List<? extends Object> mylist = new ArrayList<Object>(); mylist.add('Java'); // compile error }
The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing. In this case what purpose does the above fulfil ??
Let’s say you have an interface and two classes:
Then you have classes that return a list as a result:
It’s a good solution, when you need ‘covariant returns’, but you return collections instead of your own objects. The big plus is that you don’t have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned – as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn’t make any sense.
So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only.