Dip*_*pta 5 java generics collections covariance contravariance
我正在阅读书籍Java Generics and Collections作者:Maurice Naftalin,Philip Wadler,在前两章中,我最终误会了我的头脑.我无法弄清楚答案.
在通话中:
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]");
Run Code Online (Sandbox Code Playgroud)
在调用函数'copy'期间:
第一个参数:?= Object
2nd参数:?= Integer
但是T的数据类型是什么?如何基于擦除实现由jvm决定?
书中说:在Collections.copy(obj,ints)行中,类型参数T被认为是Number.允许调用,因为objs的类型为List <Object>,它是List <?的子类型.super Number>(因为Object是超类所需的Number的超类型)而ints的类型为List <Integer>,它是List <?的子类型.extends Number>(因为Integer是Number的子类型,根据extends通配符的要求).
但是当Integer实现Serializable和Comparable时,aprt从扩展Number类和Object类也是Serializable和Comparable的超类型.
那么为什么不将T视为Serializable或Comparable而不是Number,因为Substitution Principle将允许它被采用.
提前致谢.
T 是根据参数决定的,但也可以明确指定。所以,是的,它可以是可比较和可序列化的。
所有这些都是有效的:
Collections.<Number>copy(objs, ints);
Collections.<Comparable>copy(objs, ints);
Collections.<Serializable>copy(objs, ints);
Collections.<Integer>copy(objs, ints);
Collections.copy(objs, ints); // implicitly Integer
Run Code Online (Sandbox Code Playgroud)
当未指定类型时,由于java 文档<? extends Integer>中处理和解释的方式而选择整数
| 归档时间: |
|
| 查看次数: |
482 次 |
| 最近记录: |