类型参数的数据类型是如何协方差和逆变的? [英] How is the datatype of type parameter decided in covariance and contravariance?

查看:193
本文介绍了类型参数的数据类型是如何协方差和逆变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读的书籍是Java通用和集合,作者是Maurice Naftalin,Philip Wadler,在前两章中,我最终将我的头弄错了。我不能找出答案。

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.

在通话中:

 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

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

But what is the datatype of T? How is it decided by jvm based on the erasure implementation?

在书中说:在 Collections.copy (obj,ints),类型参数T取为Number。允许调用,因为 objs 具有类型List< Object>,它是List< ;?的子类型超级号> (因为Object是Number的超类型,如super所要求的),并且 ints 具有类型List< Integer>,其是List< extends Number> (因为Integer是Number的子类型,根据扩展通配符的要求)。


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).

但是由于Integer实现了Serializable和Comparable,因此aprt扩展Number类和Object类是超类型Serializable和Comparable也。



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


先感谢。

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.

推荐答案

T基于参数决定,但也可以明确指定。

T is decided based upon the arguments but can be specified explicitly as well. So, yes it can be Comparable and Serializable.

所有这些都是有效的:

     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

没有指定类型时由于< ;? extends Integer> java文档中处理和解释

When no type is specified Integer is picked due to the way <? extends Integer> is handled and explained in java documentation

这篇关于类型参数的数据类型是如何协方差和逆变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆