我试图通过阅读以下内容来学习Java泛型通配符: http:// www.angelikalanger/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: www.angelikalanger/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> srcto the same effect.
EDIT: I suspect the author to reinforce the point about the PECS principle
更多推荐
`copy(List<?super T> dest,List< ;? extends T> src)`和`
发布评论