gpt4 book ai didi

java - 类型参数的数据类型在协变和逆变中是如何确定的?

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:33 24 4
gpt4 key购买 nike

我正在阅读 Maurice Naftalin 和 Philip Wadler 合着的 Java Generics and Collections 一书,在前两章中,我的脑袋被疑惑搞得一团糟。我无法找出答案。

通话中:

 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]");

在调用函数“复制”期间:
第一个参数:?= 对象
第二个参数:?=Integer

但是 T 的数据类型是什么? jvm 是如何根据删除实现决定的?

书上说:在Collections.copy(obj,ints)这一行,取类型参数T为Number。调用是允许的,因为 objs 的类型是 List,它是 List (因为 Object 是 Number 的父类(super class)型,正如 super 所要求的那样)并且 ints 具有类型 List ,它是 List (因为根据 extends 通配符的要求,Integer 是 Number 的子类型)。

但是由于 Integer 实现了 Serializable 和 Comparable 两者,从扩展 Number 类和 Object 类也是 Serializable 和 Comparable 的父类(super class)型。

那么为什么不将 T 视为可序列化或可比较的而不是数字,因为替换原则将允许它被采用。

提前致谢。

最佳答案

http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

从“简单”示例中,JLS 表示它会选择满足其生成的所有约束的最具体的类型。

15.12.2.7 根据实际参数推断类型参数

A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection

Copy.java:11: incompatible types
found : java.lang.Integer[]
required: java.lang.String[]
String[] res = copy(Arrays.<Object>asList(2, 3.14, "four"), Arrays.asList(5, 6));
^
1 error
➜ /tmp cat Copy.java
import java.util.*;
public class Copy {
public static <T> T[] copy(List<? super T> dst, List<? extends T> src) {
for (int i = 0; i < src.size(); i++) {
dst.set(i, src.get(i));
}

return null;
}
public static void main(String[] args) {
String[] res = copy(Arrays.<Object>asList(2, 3.14, "four"), Arrays.asList(5, 6));
}

}

关于java - 类型参数的数据类型在协变和逆变中是如何确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9836272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com