如何在Java中动态创建列表? [英] How to dynamically create Lists in java?

查看:857
本文介绍了如何在Java中动态创建列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写类项目. 在我的项目中,我有飞机,机场和乘客.

I'm programming in java for a class project. In my project I have airplanes, airports and passengers.

旅客目的地机场是随机创建的,但随后我必须将其添加到该目的地的旅客列表中.

The passenger destination airport is randomly created, but then I have to add it to a List with passengers for that destination.

只要从文件中读取机场,它们就可以变化,那么我如何根据这些机场创建列表?

As long as the airports are read from a file thus they can vary, how can I create Lists according to these airports?

我想做的事情是这样的:

What I want to do is something like:

List<Passenger> passengersToJFK = new ArrayList<Passenger>();
.
.
.

if(passenger.destination == "JFK"){
   passengersToJFK.add(passenger);
}

问题是,正如我所说,机场的数量和名称可能会有所不同,因此我该如何做一个一般表达式,根据机场文件创建列表,然后根据乘客目的地将乘客添加到这些列表中机场?

The problem is that as I've said, the number and name of airports can vary, so how can I do a general expression that creates Lists according to the Airports File and then adds passengers to those Lists according to the passenger destination airport?

我可以从文件中读取机场的数量并创建相同数量的列表,但是如何给该列表赋予不同的名称?

I can get the number of Airports read from the file and create the same number of Lists, but then how do I give different names to this Lists?

预先感谢

推荐答案

您可以在以该乘客管理为中心的特定类中,保存目的地或机场与带有Map的乘客列表之间的关联的注册表.

You can keep a registry of the associations between a destination or airport and a list of passengers with a Map, in a particular class that centers this passengers management.

Map<String,List<Passenger>> flights = new HashMap<String,List<Passenger>>();

然后,每当您要添加新目的地时,都将放置一个新的空列表,然后

Then, whenever you want to add a new destination you put a new empty list and

public void addDestination(String newDestination) {
    flights.put(newDestination, new ArrayList<Passenger>());
}

要添加乘客时,您可以根据String表示的目的地获取乘客列表.

When you want to add a passenger, you obtain the passenger list based on the destination represented by a String.

public void addPassengerToDestination(String destination, Passenger passenger) {
    if(flights.containsKey(destination))
        flights.get(destination).add(passenger);        
}

我建议您更深入地研究一些特定的多功能Java类,例如列表,地图和集合.

I suggest you dig a little deeper into some particular multi-purpose Java classes, such as Lists, Maps and Sets.

这篇关于如何在Java中动态创建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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