Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Interfaces in Java

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?

like image 796
Pijusn Avatar asked Sep 18 '12 20:09

Pijusn


1 Answers

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.

like image 198
Simon Forsberg Avatar answered Sep 25 '22 07:09

Simon Forsberg