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:
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
Cthat also would implementA, you can’t mix the items in the array so that parts of it are of typeBand parts of it are of typeC.Also, as pointed out in the comments below, you will not be able to add an object to the list from within this method.