我正在尝试深入了解下限通配符的用法。我正在尝试编写一个通用方法 copy
它复制了一个 List
的内容给另一个。我想出了这个方法签名:
<T> void copy(List<T> dest, List<? extends T> src)
我认为这个签名很全面,可以解决所有场景。但是,我看到在 Java Collections 类中,方法签名是这样的:
<T> void copy(List<? super T> dest, List<? extends T> src)
我不明白他们为什么使用 List<? super T> dest
而不仅仅是 List<T> dest
.他们的签名是否有一些额外的灵 active ?
没有显式类型见证就没有实际区别。
如果没有像 Eran 所做的那样指定类型见证,这两种方法在灵 active 上没有差异。
本质上,的使用? super T
over T
只是风格上的差异,但它是更好的实践,正如通过应用一些好的代码原则可以看出的那样:
使用? Java tutorials 也推荐 super T
(他们甚至使用 copy
函数):
For purposes of this discussion, it is helpful to think of variables as providing one of two functions:
An "In" Variable
An "in" variable serves up data to the code. Imagine a copy
method with two arguments: copy(src, dest)
. The src
argument provides the data to be copied, so it is the "in" parameter.
An "Out" Variable
An "out" variable holds data for use elsewhere. In the copy
example, copy(src, dest)
, the dest
argument accepts data, so it is the "out" parameter.
You can use the "in" and "out" principle when deciding whether to use a wildcard and what type of wildcard is appropriate. The following list provides the guidelines to follow:
Wildcard Guidelines:
- An "in" variable is defined with an upper bounded wildcard, using the
extends
keyword.
- An "out" variable is defined with a lower bounded
wildcard, using the
super
keyword.