-2

My problem is: I created an Arraylist serviceList

Both service1 and service2 are 2 seperate objects from 2 classes but they have the same "execute" method:

public Service1 service1;
public Service2 service2;

/*Then I add element to Arraylist:*/
serviceList.add(0, service1);
serviceList.add(1, service2);

/*then how can I run "excute" method of service1 and service2?
something like this:*/
for(Object service: serviceList){
    service.execute();
}

I tried with ArrayList< Class> but it was a deadend. Thanks for your answer :D

Hai Nguyen
  • 17
  • 2
  • 3
    you declare them as Object, Object doesn't provide an execute method. so either you cast your object within your loop, or you declare them as the right type – Stultuske Dec 29 '21 at 08:49

2 Answers2

3

Introduce an interface:

interface Service {
  void execute();
}

class Service1 implements Service { ... }
class Service2 implements Service { ... }

List<Service> serviceList = ...

for (Service service: serviceList) {
  service.execute();
}
tgdavies
  • 10,307
  • 4
  • 35
  • 40
  • 1
    Don't even need an explicit loop with that... `serviceList.forEach(Service::execute)` – Shawn Dec 29 '21 at 09:02
0

Firstly, ArrayList<T> only can accept the declared type T, so you cannot add objects of a different type, say K into the same ArrayList.

Solution 1
A solution for your need could be to declare ArrayList<Object> list and then add the two services.

Solution 2
Now, because you want a common execute method, it would be natural for your Service1 and Service2 classes to implement some interface, say Service to achieve a unique execute method implementation for each class. And you can declare your ArrayList as ArrayList<Service> list

roksui
  • 109
  • 1
  • 8