I have this bit of ( counter-intuitive ) observations about generic wildcard notation used in collections.
The purpose of the wildcard notation List<? extends T> is to allow the assignment of a List (of subtypes of T) to the reference of List of ‘? of T’. Its purpose is not to specifically allow the adding of elements of subtypes of T into the List ( of ‘? of T’ ) , which is possible even in a List<T>.
List<Number> list = new ArrayList<Integer>(); // invalid , List<Integer> is not assignable to List<Number>
List<Number> list = new ArrayList<Number>() ; // OK
list.add(new Integer(1)); // valid , '? extends Number' not needed!
List<? extends Number> list1 = new ArrayList<Integer>(); // Valid , because of notation '? extends Number'
Is my observation correct ?
Yes, your observation is correct. However, in the case you show, it’s not very useful (you’re electing to ignore useful information about the list). The assignment is more useful when it’s implicit as you call a library function.
For example, say you had a library function that closed a collection of InputStreams. You could accept a
List<InputStream>, but that is unnecessarily restrictive. You could instead do this:Now you can pass in a
List<FileInputStream>instead.