Re: Q:Generics
Kari Laine wrote:
The book is "Java Generics and Collections", which I am reading at the
O'Reilly Safari. The one other book mentioned seems to be at Safari
also, so I have more reading and testing to do.
Here is the clip of the part causing me problems.
2.3. Wildcards with super
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));
}
}
Here is a sample call.
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]");
Collections.copy(objs, ints);
Collections.<Object>copy(objs, ints);
Collections.<Number>copy(objs, ints);
Collections.<Integer>copy(objs, ints);
We could also declare the method with several possible signatures.
public static<T> void copy(List<T> dst, List<T> src)
public static<T> void copy(List<T> dst, List<? extends T> src)
public static<T> void copy(List<? super T> dst, List<T> src)
public static<T> void copy(List<? super T> dst, List<? extends T> src)
The first of these is too restrictive, as it only permits calls when the
destination and source have exactly the same type. The remaining three
are equivalent for calls that use implicit type parameters, but differ
for explicit type parameters. For the example calls above, the second
signature works only when the type parameter is Object, the third
signature works only when the type parameter is Integer, and the last
signature works (as we have seen) for all three type parameters???i.e.,
Object, Number, and Integer. Always use wildcards where you can in a
signature, since this permits the widest range of calls.
As I mentioned. I did not understand why the second works only with
Object and the third only when type is Integer.
They mean specifically for the example instance 'objs' and 'ints', not for all
code everywhere.
Because, as Mike Schilling pointed out, 'Object' is they only type shared by
'objs' and 'ints' base types that meets the restrictions imposed by the second
form, and 'Integer' is the only type shared by 'objs' and 'ints' that meets
the third's. 'Number' doesn't work for those two given 'objs' and 'ints'.
If the base types of the specific example lists had been different, the
specific types accepted would have been different from 'Object' and 'Integer'.
--
Lew