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 t开发者_如何学JAVAhere 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
Just do it.
Seriously, a class will implicitly cast to an interface for which it implements.
Edit
In case you needed an example:
import java.util.*;
public class Sandbox {
public static void main(String[] args) {
final ArrayList<Integer> list = new ArrayList<Integer>(5);
Collections.addAll(list, 1, 2, 3, 4, 5);
printAll(list);
}
private static void printAll(Collection<Integer> collection) {
for (Integer num : collection)
System.out.println(num);
}
}
class ArrayList<E> implements List<E>
and interface List<E> extends Collection<E>
, so an ArrayList<Integer>
is-a Collection<Integer>
.
This is what is called "subtyping".
Note, however, that even though Integer extends Number
, a List<Integer>
is-not-a List<Number>
. It is, however, a List<? extends Number>
. That is, generics in Java is invariant; it's not covariant.
Arrays on the other hand, are covariant. An Integer[]
is-a Number[]
.
References
- Wikipedia: Subtype polymorphism
- JLS 4.10 Subtyping
- JLS 4.10.2 Subtyping among Class and Interface Types
- JLS 4.10.3 Subtyping among Array Types
- Java Tutorials/Generics/Subtyping
Related questions
- What is the difference between
<E extends Number>
and<Number>
? - Covariance and contravariance in programming languages
- What is the purpose of interfaces? [closed]
- How will I know when to create an interface?
- Why doesn’t Java Map extends Collection?
精彩评论