How to dynamically create Lists in java?

11,693

Solution 1

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.

Solution 2

I would probably create a Map of airports with airport name as the key and a List of passengers as the value.

e.g.

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

airports.put("JFK", passengersToJFK);
Share:
11,693
Joaocdn
Author by

Joaocdn

Updated on June 15, 2022

Comments

  • Joaocdn
    Joaocdn almost 2 years

    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