I have an interface A:
interface A {
}
Then I have a class B:
class B implements A {
}
Then I have a method that uses a list of A:
void process(ArrayList<A> myList) {
}
I want to pass it a list of B:
ArrayList<B> items = new ArrayList<B>();
items.add(new B());
process(items);
But then there is an error that types do not match. I understand why. ArrayList
is a type itself and it has not function to convert from ArrayList<B>
to ArrayList<A>
. Is there a quick and resource-wise light way to form a new array that is suitable to be passed to my process
method?
I think the easiest solution is to change one of the methods to:
void process(ArrayList<? extends A> myList) {
}
However, be aware that with this solution the entire list needs to be of the same type. That is, if you would have a class C
that also would implement A
, you can't mix the items in the array so that parts of it are of type B
and parts of it are of type C
.
Also, as pointed out in the comments below, you will not be able to add an object to the list from within this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With