Multilists linked with ArrayList

0

I am creating a program that simulates the functioning of a metro network.

I have reached a point where I have to create the lines from a graph where I have all the stops and their respective connections. I have considered the option of creating a linked multilist but the task is very heavy for the utility that I want to give it.

My question is: Can we create an ArrayList, that it is Arraylist type and that it contains stop objects (The explanation of the stopped object is not relevant for my problem, I store the data and characteristics of each stop). Come on, what I want to do would be something like this:

ArrayList <ArrayList><Parada> lineasMetro = new ArrayList<>();

But it is not possible to do it this way.

    
asked by ignacio aranguren 05.12.2018 в 19:40
source

2 answers

3

Of course you can:

public class Parada {

    private String nombre;

    public Parada(String nombre){
        this.nombre=nombre;
    }
    /**
     * @return the nombre
     */
    public String getNombre() {
        return nombre;
    }
    /**
     * @param nombre the nombre to set
     */
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

}

And where you are going to occupy it in the following way (ArrayList of ArrayList of Stop objects):

ArrayList<ArrayList<Parada>> redMetro = new ArrayList<ArrayList<Parada>>();

//Linea 1
ArrayList<Parada> linea1 = new ArrayList<Parada>();

//Estaciones linea 1
Parada paradaa= new Parada("Centro");
linea1.add(paradaa);
Parada paradab= new Parada("Norte");
linea1.add(paradab);
Parada paradac= new Parada("Sur");
linea1.add(paradac);

redMetro.add(linea1);

//Linea 2
ArrayList<Parada> linea2 = new ArrayList<Parada>();

//Estaciones linea 2
Parada paradad= new Parada("Poniente");
linea2.add(paradad);
Parada paradae= new Parada("Centro");
linea2.add(paradae);
Parada paradaf= new Parada("Oriente");
linea2.add(paradaf);

redMetro.add(linea2);

To iterate over them you can do the following:

    int numeroLinea = 0;
    for(ArrayList<Parada> linea: redMetro){
        numeroLinea++;
        System.out.println("Linea: "+numeroLinea);
        for(Parada parada: linea){
            System.out.println(parada.getNombre());
        }
    }

Greetings from CDMX

    
answered by 05.12.2018 / 20:06
source
0

Simply

ArrayList<Parada> lineasMetro = new ArrayList<>();

or better yet:

List<Parada> lineasMetro = new ArrayList<>();

More info: Generics

EDIT: What you need is a Map .

Ex:

Map<Integer, Parada> lineasMetro = new HashMap<>();

or

Map<Integer, List<Parada>> lineasMetro = new HashMap<>();

Or whatever you need.

To see other implementations of Map: Maps

    
answered by 05.12.2018 в 19:47