How to dynamically create Lists in java?

arrays, java, list

Solution

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

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

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

Problem

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? Thanks in advance

Original source