java - 什么是多级通配符?语法困惑

标签 java generics wildcard

我正在从 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 type Pair<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 form Pair<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 form Pair<String,?> . Compatible instantiations are Collection<Pair<String,Long>> , Collection<Pair<String,String>> , Collection<Pair<String,Object>> , or Collection<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.

我对以下几点感到困惑。

  1. 有人可以举例详细说明这三句话吗?我完全迷失在语法中
  2. 文档说,para-1是泛型的具体实例,而other不是具体实例?怎么样?
  3. 自上而下阅读通配符是什么意思?
  4. 多级通配符有什么优势?

有人可以详细说明这些要点吗?谢谢。

最佳答案

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>> , 外层 ListList<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/

相关文章:

Swift 通用转换错误

java - 为什么泛型接口(interface)不能用作类型参数?

java - Key-Value 参数与通配符匹配

java - 告诉 Intellij 该类是库的一部分,因此方法未使用是正常的

java - 指定要在 JPA 实体而不是类中使用的转换器的特定实例

java - Java 中的 OpenCV 用于图像过滤

Mysql - 如何对刺痛的单词进行通配符搜索

java - 在大容量应用程序中使用 Class.forName(...) 是否会导致性能下降?

java - 为什么我不能从使用泛型创建的类中调用方法? java

java - 当类型为通配符时,如何将泛型结果用作泛型参数?