Reputation: 4982
Why there is <?e extends T>
instead of <T>
in unmodifiable APIs of java.util.Collections
e.g. consider unmodifiableLis API
public static <T> List<T> unmodifiableList(List<? extends T> list)
Why not, just
public static <T> List<T> unmodifiableList(List<T> list)
Edit:
This is not duplicate of When do Java generics require instead of and is there any downside of switching. That question intend to find the importance of <? extends T>
over <T>
and what would be the impact if change is done from one to other. I understand the difference in both syntax (<? extends T>
and <T>
), however in case of unmodifiable collection APIs, context (and hence my question) is different.
Upvotes: 2
Views: 198
Reputation: 234807
It's so you can do things like this:
List<Integer> intList = new ArrayList<Integer>();
// . . . populate intList
// now create an unmodifiable version:
List<Number> numList = Collections.unmodifiableList(intList);
Note that because generics are not covariant, so you cannot assign from a List<Integer>
to a List<Number>
:
numList = intList;
even though each element would be assignment-compatible. If you changed the signature of unmodifiableList
as you suggest, it would run into the same problem (since the return type in my example would be forced to be List<Integer>
once the parameter was bound).
Upvotes: 3