如何将 ArrayList 传递给以集合作为输入的方法
我想将一些 ArrayList
X 传递到方法 a(Collection
中,该方法将 Collection
作为输入。
我该怎么做?我认为 ArrayList 是一个 Collection,因此我应该能够“只是这样做”,但看起来 Collection 是一个接口,而 ArrayList 实现了这个接口。我能做些什么来让这项工作成功吗……如果你理解这个理论,这也将帮助我和可能的许多其他人。
谢谢
I want to pass some ArrayList<Integer>
X into method a(Collection<Integer> someCol)
that takes Collection<Integer>
as an input.
How can I do this? I thought an ArrayList was a Collection and thus I should be able to "just do it" but it seems that Collection is an interface and ArrayList implements this interface. Is there something I can do to make this work ... if you understand the theory that would also help me and possibly lots of other people.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
去做就对了。
认真地说,一个类将隐式转换为它所实现的接口。
编辑
如果您需要示例:
Just do it.
Seriously, a class will implicitly cast to an interface for which it implements.
Edit
In case you needed an example:
类 ArrayList;实现 List
和接口列表;扩展 Collection
,因此ArrayList
是一个Collection
。这就是所谓的“子类型化”。
但请注意,即使
Integer extends Number
,List
不是List
。然而,它是一个List
。也就是说,Java中的泛型是不变的;它不是协变的。另一方面,数组是协变的。
Integer[]
是一个Number[]
。参考文献
相关问题
和
之间的区别?class ArrayList<E> implements List<E>
andinterface List<E> extends Collection<E>
, so anArrayList<Integer>
is-aCollection<Integer>
.This is what is called "subtyping".
Note, however, that even though
Integer extends Number
, aList<Integer>
is-not-aList<Number>
. It is, however, aList<? extends Number>
. That is, generics in Java is invariant; it's not covariant.Arrays on the other hand, are covariant. An
Integer[]
is-aNumber[]
.References
Related questions
<E extends Number>
and<Number>
?