java - 为什么 Java 通配符比 use-site variance 更强大?

标签 java generics types type-systems type-theory

我经常读到 Java 通配符是一个比使用点差异的概念更强大的概念。但在我的理解中,Java 通配符的概念完全等同于使用点差异的概念。

那么两者有什么区别呢?您能否给出一个具体示例,该示例可以使用 Java 通配符但不能使用站点变体?

例如How does Java's use-site variance compare to C#'s declaration site variance?中的第一个答案是提出我的问题的一个例子:

First off, if I remember correctly use-site variance is strictly more powerful than declaration-site variance (although at the cost of concision), or at least Java's wildcards are (which are actually more powerful than use-site variance).

但是,答案并没有说明有什么区别,只是说有一个。

编辑: 我发现的第一个区别 here (第 112 页上的第一段)似乎是使用站点差异完全不允许调用在错误位置具有类型参数的方法,而通配符允许使用某些类型调用它。例如,您不能调用 add , 在 List<? extends String> 上.使用 Java 通配符,您可以调用 add在这样的类(class)上,但你必须使用 null作为参数。对于逆变,可以调用任何返回逆变参数的方法,但必须假定返回类型为 Object .但这是唯一的区别吗?

最佳答案

在阅读了很多关于这个主题的内容之后,我似乎在 Altidor、Reichenbach 和 Smaragdakis 的 this 论文中找到了答案。与 use-site variance 相比,Java 泛型的主要补充是捕获转换,它允许在类型参数中捕获以前未知的通配符类型。论文中的这个例子最好地解释了这一点:

One complication is that Java wildcards are not merely use-site variance, but also include mechanisms inspired by existential typing mechanisms. Wildcard capture is the process of passing an unknown type, hidden by a wildcard, as a type parameter in a method invocation. Consider the following method, which swaps the order the two elements at the top of a stack.

  <E> void swapLastTwo(Stack<E> stack) { 
        E elem1 = stack.pop();
        E elem2 = stack.pop();
        stack.push(elem2); 
        stack.push(elem1); 
   }

Although a programmer may want to pass an object of type Stack<?> as a value argument to the swapLastTwo method, the type parameter to pass for E cannot be manually specified because the type hidden by ? cannot be named by the programmer. However, passing a Stack<?> type checks because Java allows the compiler to automatically generate a name for the unknown type (capture conversion) and use this name in a method invocation.

也就是说,在 Java 中,我们可以使用 swapLastTwo() 作为输入参数来调用 Stack<?>。然后编译器将 ? 捕获到类型变量 E 中,因此知道我们可以在我们刚刚编辑 push 的元素上调用 pop。由于使用位置差异,我们无法执行此操作,因为类型系统会丢失从 pop 返回的元素属于 push 预期类型的​​信息。

请注意,我们必须使用类型参数来捕获类型。不这样做将使类型检查器将从 pop 返回的类型与 push 预期的类型不同。

例如,这不会在 Java 中编译:

Stack<?> s = ...;
s.push(s.pop());

这里,s的元素的类型会被捕获到两个不同的新类型变量中(在eclipse中称为capture 1 of ?capture 2 of ?。类型检查器将这些类型变量视为不同的,代码不会编译。通过使用泛型方法我们可以将 ? 的类型捕获到允许调用 pushpop 的命名参数中。

我不确定这是否是 Java 通配符和“通常”(不管是什么)使用站点差异之间的唯一区别,但至少这似乎是一个非常显着的区别。

关于java - 为什么 Java 通配符比 use-site variance 更强大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24807562/

相关文章:

java - 如何更改所使用的房间

Java多线程应用程序只使用一个核心

java - 在父类(super class)构造函数中将 'this' 转换为子类

java - 对象化,Key<T> 可能吗?解决方法?

c - 如何根据条件使用不同的数据类型变量?

java - Spring 3 如何处理具有相同内容的多语言 URL

generics - 具有静态成员的 F# 泛型类型。这可能吗?

java - JAXB - marshall 通用类型(日期)

elasticsearch - 在 Elasticsearch 中聚合不同数据类型的嵌套字段

R 字符因子到数字向量