简体   繁体   中英

How can I execute method of an Object in Arraylist?

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

Introduce an interface:

interface Service {
  void execute();
}

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

List<Service> serviceList = ...

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM