Reputation: 92
my problem is the following:
I have an executor that runs some long running task on an Arraylist of custom Objects. I want to able to feed the executor Arraylists of different class types each of which implements an interface so that the executor knows what to do with any compatible class instance.
class MyExectorService{
....
interface MyInterface{
String getData();
}
}
class A implements MyExecutor.MyInterface {} ....
class B implements MyExecutor.MyInterface {} ....
my executer singleton has a method signature:
public void submitList(ArrayList<MyInterface> list, ....)
When I have an ArrayList of class A, or B, etc. I get a wrong parameter type exception from the compiler. I can create some function that just returns a raw type of ArrayList to convert it before submitting it
e.g.
public static ArrayList getRaw(ArrayList list){
return list;
}
...MyExecutorService.getInstance().submitList(getRaw(aa /* arraylist of class A /*),...)
but what is the correct way to do this please?
Upvotes: 0
Views: 192
Reputation:
When I have an ArrayList of class A, or B, etc.
Use a List<MyExectorService.MyInterface>
instead.
List<MyExectorService.MyInterface> l = new ArrayList<>();
l.add(new A());
l.add(new B());
submitList(l);
Upvotes: 0
Reputation: 59203
Your submitList
method expects strictly an arraylist whose generic type is MyInterface
. That is different from an arraylist whose generic type is some subtype of MyInterface
. You could change it to this:
private void submitList(List<? extends MyInterface> list, ...)
That specifies that the first parameter must be a list whose generic type is some subtype of MyInterface
. Also, in general it is recommended to accept List
rather than ArrayList
as a parameter (i.e. program to an interface), because most of the time, you don't care which implementation of List
you are being given when the method is called.
Upvotes: 7