I was reading the book Java Generics and Collections By Maurice Naftalin, Philip Wadler, and within the first two chapters I ended up in having my head messed up with doubts. I was not able to figure out the answers.
In the call:
public static <T> void copy(List<? super T> dst, List<? extends T> src) {
for (int i = 0; i < src.size(); i++) {
dst.set(i, src.get(i));
}
}
List<Object> objs = Arrays.<Object>asList(2, 3.14, "four");
List<Integer> ints = Arrays.asList(5, 6);
Collections.copy(objs, ints);
assert objs.toString().equals("[5, 6, four]");
During call to the function 'copy':
1st parameter: ?= Object
2nd Parameter: ?=Integer
But what is the datatype of T? How is it decided by jvm based on the erasure implementation?
It is said in the book that: In the line Collections.copy(obj,ints), the type parameter T is taken to be Number. The call is permitted because objs has type List<Object>, which is a subtype of List<? super Number> (since Object is a supertype of Number, as required by the super) and ints has type List<Integer>, which is a subtype of List<? extends Number> (since Integer is a subtype of Number, as required by the extends wildcard).
But as Integer implements Serializable and Comparable both, aprt from extending Number class and Object class is the super type of Serializable and Comparable also.
So why not that T is taken as Serializable or Comparable instead of Number, because the Substitution Principle will allow it to be taken.
Thanks in advance.