`copy(List<?super T> dest,List&lt ;? extends T> src)`和`copy(List< T> dest,List&lt ;? extends T> src) [英] Differences between `copy(List<? super T> dest, List<? extends T> src) ` and `copy(List<T> dest, List<? extends T> src)`

查看:132
本文介绍了`copy(List<?super T> dest,List&lt ;? extends T> src)`和`copy(List< T> dest,List&lt ;? extends T> src)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过阅读以下内容来学习Java泛型通配符:
http:// www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ103



材料中有一个例子:

  public class Collections {
public static< T> void copy(List< ;? super T> dest,List< ;? extends T> src){
for(int i = 0; i< src.size(); i ++)
dest.set(i ,为src.get(I));


$ / code>

我想知道是否可以将方法签名更改为如下所示:

  public static< T> void copy(List< ;? super T> dest,List< ;? extends T> src){



  public static< T> void copy(List< T> dest,List< ;? extends T> src){

这两个方法之间的区别是什么?



示例将不胜感激。 p>你是对的。在这种情况下,两个参数的类型参数用于表示 dest 必须包含 src 。因此,如果您说 src 包含<?如果 $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $ T $您也可以用其他方式表达,即:

 列表<?超T> dest,List< T> src 

达到同样的效果。

编辑:我怀疑作者强调了关于 PECS原则


I am trying to learn Java Generics wildcard by reading the following: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ103

There is one example in the material:

public class Collections { 
  public static <T> void copy (List<? super T> dest, List<? extends T> src) {
      for (int i=0; i<src.size(); i++) 
        dest.set(i,src.get(i)); 
  } 
}

I was wondering if I can change the method signature as the following:

  public static <T> void copy(List<? super T> dest, List<? extends T> src) {

  public static <T> void copy(List<T> dest, List<? extends T> src) {

Are there any differences between these two method sinatures?

Examples would be appreciated.

解决方案

You are correct. In this case the two parameter's Type Arguments are being used to express the relationship that dest must contain objects of a super type of the objects in src. Therefore if you say src contains <? extends T> then it's sufficient to say that dest contains objects of T.

You can also express it the other way round, namely:

List<? super T> dest, List<T> src

to the same effect.

EDIT: I suspect the author to reinforce the point about the PECS principle

这篇关于`copy(List&lt;?super T&gt; dest,List&lt ;? extends T&gt; src)`和`copy(List&lt; T&gt; dest,List&lt ;? extends T&gt; src)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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