Java 集合接口 addAll() 方法签名
如果 Java Collection Interface 有像这样的 addAll 方法签名
<T extends E> boolean addAll(Collection<T> c);
而不是 boolean addAll(Collection c);
?
谢谢
-阿比迪
What difference would it make if Java Collection Interface has addAll method signature like this
<T extends E> boolean addAll(Collection<T> c);
rather thanboolean addAll(Collection<? extends E> c);
?
Thanks
-Abidi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在这种情况下,使用
或
对于addAll
的用户来说是等效的。我认为使用前一种符号是为了清楚起见,因为使用
会使addAll
的签名更加复杂。In this case, having
<?>
or<T>
is equivalent for users ofaddAll
.I think that the former notation was used for clarity, because using
<T>
makes the signature ofaddAll
more complicated.以这个测试界面为例:
这是字节代码:
正如您所看到的,生成的字节代码没有任何区别(除了生成的调试代码)。因此,如果两个版本是等效的,您不妨坚持使用更容易理解的版本。
Take this test interface:
Here's the byte code:
As you can see there's no difference in the resulting byte code (apart from the generated debug code). So if the two versions are equivalent, you might as well stick with the version that's easier to understand.
问题是,
中的 c)
完全没有必要,因为T
是这样的: boolean addAll(CollectionaddAll
不关心E
的具体子类型它给出的集合包含。它所关心的是它给定的集合包含E
的某些子类型,这正是Collection
的意思。您不应该向方法引入不必要的泛型类型。
The thing is, the
T
in<T extends E> boolean addAll(Collection<T> c)
is completely unnecessary, becauseaddAll
doesn't care what specific subtype ofE
the collection it's given contains. All it cares is that the collection it's given contains some subtype ofE
, which is exactly whatCollection<? extends E>
means.You shouldn't introduce unnecessary generic types to a method.
如果您使用显式类 T,则无法将通配符集合传递给该方法,而您可能想要并且应该能够这样做。
If you used an explicit class T, then you could not pass a wildcarded collection to the method, which is something that you may want to do and should be able to.
基本上,当类型变量
T
仅在参数类型中的某个位置使用时,您可以安全地将其更改为?
。Basically, when the type variable
T
is only going to be used in one place somewhere in the types of the parameters, you can safely change it to?
.我认为这不会编译。一个方法不能同时有两种返回类型(
和boolean
)。I don't think that would compile. A method cannot have two return types (
<T>
andboolean
) at the same time.