简体   繁体   中英

Java - Loop through instances of a class rather than calling a method for each separate instance

I am starting to learn Java and would like to know how to loop through instances of a class when calling a method, instead of separately calling the method for each instance, like below:

String potentialFlight = (Flight1.getLocations(response));
if (potentialFlight != null) {
    System.out.println(potentialFlight);
}

potentialFlight = (Flight2.getLocations(response));
if (potentialFlight != null) {
    System.out.println(potentialFlight);
}

For clarity, Flight1 and Flight2 are instances of a class Flight . Response is the user input parsed into the method and will be a location, which I will use the getLocations method to return any potential flights departing from that location.

If you need more of my code, please comment below.

Thanks for you help!

You could put all your instances into an Array(List), and use a foreach construction to iterate over all instances.

For example:

Flight[] flights = { Flight1, Flight2 };
for (Flight f : flights) {
    String potentialFlight = (f.getLocations(response));
    if (potentialFlight != null) {
        System.out.println(potentialFlight);
    }
}

solution:

Stream.of(flights)
        .map(f -> f.getLocations(response))
        .filter(f -> f != null)
        .forEach(System.out::println);

You should probably use interfaces for flexible handling eg:

public interface IFlyingObject {

    Object getLocations(Object o);

}

public class Plane implements IFlyingObject{
    @Override
    public Object getLocations(Object o) {
        return null;
    }
}
public class Helicopter implements IFlyingObject{
    @Override
    public Object getLocations(Object o) {
        return null;
    }
}
public static void main(String[] args) {
    List<IFlyingObject> flightObjects = new ArrayList<IFlyingObject>();
    flightObjects.add(new Plane());
    flightObjects.add(new Helicopter());
    Object response = new Object();
    for (IFlyingObject f : flightObjects) {
        Object result = f.getLocations(response);
    }
}

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