How to pass generic collections to methods
How do pass a generic collection of objects to my methods as detailed below:
class Test {
class X<T> {
}
class XI extends X<Int开发者_运维知识库eger> {
}
class XD extends X<Double> {
}
class S {
Collection<X<?>> items;
public void addX(Iterable<X<?>> x) {
// Error: The method addAll(Collection<? extends Test.X<?>>)
// in the type Collection<Test.X<?>>
// is not applicable for the arguments (Iterable<Test.X<?>>)
items.addAll(x);
}
}
void fooo() {
X<?>[] x = new X<?>[] {new XI(), new XD()};
S s = new S();
// The method addX(Iterable<Test.X<?>>)
// in the type Test.S is not applicable for the arguments (Test.X<?>[])
s.addX(x);
}
}
Thanks
Collection.addAll
expects a Collection
but you pass it an Iterable
...
You can convert your array to a List (which is a Collection) by using the Arrays class:
Arrays.asList(myArray);
精彩评论