我正在从 AngelikaLangerGenericsFaq 读取多级通配符 | .我很困惑 关于语法。文件说
The type
Collection<Pair<String,?>>
is a concrete instantiation of the generic Collection interface. It is a heterogenous collection of pairs of different types. It can contain elements of typePair<String,Long>
,Pair<String,Date>
,Pair<String,Object>
,Pair<String,String>
, and so on and so forth. In other words,Collection<Pair<String,?>>
contains a mix of pairs of different types of the formPair<String,?>
.The type
Collection<? extends Pair<String,?>>
is a wildcard parameterized type; it does NOT stand for a concrete parameterized type. It stands for a representative from the family of collections that are instantiations of the Collection interface, where the type argument is of the formPair<String,?>
. Compatible instantiations areCollection<Pair<String,Long>>
,Collection<Pair<String,String>>
,Collection<Pair<String,Object>>
, orCollection<Pair<String,?>>
. In other words, we do not know which instantiation of Collection it stands for.As a rule of thumb, you have to read multi-level wildcards top-down.
我对以下几点感到困惑。
- 有人可以举例详细说明这三句话吗?我完全迷失在语法中
- 文档说,para-1是泛型的具体实例,而other不是具体实例?怎么样?
- 自上而下阅读通配符是什么意思?
- 多级通配符有什么优势?
有人可以详细说明这些要点吗?谢谢。
最佳答案
Can someone elaborate on these three quotes with example. I am totally lost into the syntax
好吧,在这里再次写下这 3 个引号是没有意义的,因为我无法给出比这更好的解释。相反,我将尝试在下面回答您的其他问题,那么您可能也会理解这个问题的答案。如果没有,您可以再次提出您的问题,我会尝试进一步详细说明。
Document says, para-1 is the concrete instantiation of a generic type and other is not the concrete instantiation? How is that?
具体实例化是所有类型参数都是具体类型,并且在编译时已知的实例化。例如,List<String>
是一个具体的实例,因为String
是具体类型。它的类型在编译时是已知的。鉴于,List<? extends Number>
不是具体类型,因为 ? extends Number
可以是扩展 Number
的任何类型.因此,它的类型在编译时是未知的。同样,Map<String, Integer>
是泛型类型的具体实例 Map<K, V>
.
在多级类型参数的情况下,List<List<? extends Number>>
, 外层 List
是 List<E>
的具体实例,因为已知元素的类型是 List
在编译时,虽然内部 List
是通配符实例化,因为存储的元素类型可以是 Integer
, Double
, Number
的任何子类.但是那段只是在谈论外部类型。并且外部类型只能包含 List
类型。
所以第一段说,它是Pair
的异构集合,因为 Pair
的实际类型参数可以是任何东西,但肯定是Pair
没有别的。
What does it mean to read the wild-cards top down?
通俗地说,就是从左到右。在确定参数化类型的类型时,您首先会看到最外层的类型参数。然后,如果该类型参数本身是参数化类型,那么您将转到该参数化类型的类型参数。因此,我们从左到右读取类型参数。
What is the advantage of multi-level wild cards?
假设您要创建一个水果列表。现在你的内心List
可以包含任何种类的水果。 苹果也是水果,香蕉也是水果。因此,您必须确保获得所有这些。现在,由于泛型类型是不变的,从某种意义上说,List<Apple>
与 List<Fruit>
不同, 你不能添加 List<Apple>
如果您的列表类型是 List<List<Fruit>>
.为此,您需要使用 wildcards
像这样 - List<List<? extends Fruit>>
, 现在可以取 List<Apple>
, List<Banana>
, 任何水果的列表。
关于java - 什么是多级通配符?语法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18194956/