I am trying to learn Java Generics wildcard by reading the following: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ103
There is one example in the material:
public class Collections {
public static <T> void copy (List<? super T> dest, List<? extends T> src) {
for (int i=0; i<src.size(); i++)
dest.set(i,src.get(i));
}
}
I was wondering if I can change the method signature as the following:
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
↓
public static <T> void copy(List<T> dest, List<? extends T> src) {
Are there any differences between these two method sinatures?
Examples would be appreciated.
You are correct. In this case the two parameter's Type Arguments are being used to express the relationship that dest
must contain objects of a super type of the objects in src
. Therefore if you say src
contains <? extends T>
then it's sufficient to say that dest
contains objects of T.
You can also express it the other way round, namely:
List<? super T> dest, List<T> src
to the same effect.
EDIT: I suspect the author to reinforce the point about the PECS principle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With