我正在阅读来自OracleDocGenericMethod的通用方法,但是当文档中提到何时使用通配符和何时使用通用方法进行比较时,我感到相当困惑。
interface Collection<E> { public boolean containsAll(Collection<?> c); public boolean addAll(Collection<? extends E> c); }
We could have used generic methods here instead:
interface Collection<E> { public <T> boolean containsAll(Collection<T> c); public <T extends E> boolean addAll(Collection<T> c); // Hey, type variables can have bounds too! }
[…] This tells us that the type argument is being used for polymorphism; its only effect is to allow a variety of actual argument types to be used at different invocation sites. If that is the case, one should use wildcards. Wildcards are designed to support flexible subtyping, which is what we're trying to express here.
我们是否认为像 (Collection<? extends E> c);
这样的通配符也支持多态性呢?那么为什么泛型方法的使用被认为不好呢?
接下来,文中进一步说明:
泛型方法允许类型参数用于表示一个或多个参数及/或其返回类型之间的依赖关系。如果没有这样的依赖关系,则不应使用泛型方法。
这是什么意思?
他们提供了以下示例:
class Collections { public static <T> void copy(List<T> dest, List<? extends T> src) { ... }
[…]
We could have written the signature for this method another way, without using wildcards at all:
class Collections { public static <T, S extends T> void copy(List<T> dest, List<S> src) { ... }
这篇文档不鼓励使用第二种声明方式,而是推荐使用第一种语法?第一种和第二种声明有什么区别?它们似乎都在做同样的事情?
能有人解释一下吗?
?
。你可以将其重写为public static <T1 extends Number, T2 extends Number> void copy(List<T1> dest, List<T2> src)
,在这种情况下,就会变得很明显发生了什么。 - kanList
中定义下限。List<T super Integer>
是无效的,也不会编译。 - Rohit Jain<T extends X & Y>
表示多重限定(multiple bounds),即T必须是X和Y的子类。 - Rohit Jain