Java-遍历类的实例,而不是为每个单独的实例调用方法 [英] Java - Loop through instances of a class rather than calling a method for each separate instance

查看:50
本文介绍了Java-遍历类的实例,而不是为每个单独的实例调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Java,想知道如何在调用方法时遍历类的实例,而不是像下面这样分别为每个实例分别调用方法:

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);
}

为清楚起见, Flight1 Flight2 是类 Flight 的实例.响应是解析到该方法中的用户输入,它将是一个位置,我将使用getLocations方法返回从该位置出发的任何潜在航班.

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.

感谢您的帮助!

推荐答案

您可以将所有实例放入Array(List)中,并使用foreach构造对所有实例进行迭代.

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

例如:

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

这篇关于Java-遍历类的实例,而不是为每个单独的实例调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆