Home > Blockchain >  How can I execute method of an Object in Arraylist?
How can I execute method of an Object in Arraylist?

Time:12-29

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

CodePudding user response:

Introduce an interface:

interface Service {
  void execute();
}

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

List<Service> serviceList = ...

for (Service service: serviceList) {
  service.execute();
}

CodePudding user response:

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

  • Related