I have an interface I, two classes A & B that implement it and a list with generic type the interface I, so it can contain both objects of type A & B.
class A implements I
class B implements I
List<I> myList
I would like to write (in a separate class) two methods process( A a ) and process( B b ) so I can loop through the list and for each element call process( i ) and java will automatically (unbox?) the object and invoke the correct method.
class D{
processList(){
for( I i : myList ){
process( i ); // invoke either process(A) or process(B) based on instanceof
}
}
public void process(A a){...}
public void process(B b){...}
}
I know I can do this by invoking 'instanceof' on each element in the list and then if-else to call the different methods, but there must be a better way.
In a MVC scenario, classes A and B are in the Model, while class D is in the Controller, thus the need for separation.
Can anyone help?
there must be a better way.
There is. Add the method process() to the interface I
. Then you can call process
on the items while you iterate the List<I>
-
List<I> list = new ArrayList<>();
// populate list with A and B instances, then
for (I i : list) {
i.process();
}
Obviously A
and B
must then provide concrete implementations of process()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.