Class similar to HashMap that provides get (int index) in Java

0

I am looking for a Java class that allows me to store two variables of the type that are joining them, but that also allows me to access them in an ascending / descending way or by index.

Searching I found the HashMap class, which fulfills the first thing I look for, but when it comes to accessing the data it contains, I do not use the get (Object key) method, since I do not know the data that this object stores .

Any suggestions?

Context:

I'm doing a little program about bus stops. I was looking for a way to match the line of the stop with the remaining minutes (until the bus reached this), then my code is as follows:

//Crea una nueva parada
EMTParada parada= new EMTParada();
    //Establece el nombre de la parada (código no necesario )
    parada.setStopName(nomParada);
    //Lectura de paradas (datos obtenidos desde un HTML, clase Document)
    for(Element a: busLineList.select("li")){
     // A la izquierda agrego el número de la linea y a la derecha los minutos restantes
        parada.setLinea(Integer.parseInt(a.getElementsByAttribute("title").text()),a.select("span.minutos"+"[0-9]").text());
    }

Method setLinea();

private HashMap linea= new HashMap<Integer,String>();

public void setLinea(int num, String string) {
    linea.put(num,string);
}
    
asked by JD0001 16.03.2017 в 11:49
source

3 answers

1

The main problem is that the class HashMap does not preserve the insertion order so you can not access it by index directly via index:

  

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

You can use instead ' LinkedHashMap ' which guarantees a Predictable iteration order and allows you to go through the list in order but, equally, does not allow access by index.

Solutions if index access is required:

One possible solution is to pass the values (not keys) to a list:

List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

or an array:

public Object getElementByIndex(LinkedHashMap map,int index){
    return map.get( (map.keySet().toArray())[ index ] );
}

but in both cases the result is not optimal.

A third more correct alternative and elegant is to create a class Pair and create a list of objects from this list. In this way you can access by index each pair of values.

Pair class:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

Example of use:

List<Pair<String, Integer>> map = new ArrayList<Pair<String, Integer>();
map.add(new Pair("Hello", 10));
map.add(new Pair("World", 20));

Pair<String, Integer> hello = map.get(0);
System.out.println("Hello string: " + hello.getL());
System.out.println("Hello integer: " + hello.getR());

exit:

Hello string: Hello
Hello integer: 10
    
answered by 16.03.2017 / 12:09
source
0

I recommend you use HashTable. For example, imagine that we created a HashTable object:

Hashtable<String,String> contadores = new Hashtable();

For example, I create a HashTable in this case to store the data I read from an XML file

SAXBuilder builder = new SAXBuilder();
        File fichero = new File("DescargaContadores.xml");
        Document document = (Document) builder.build(fichero);
        Element rootElement = document.getRootElement();
        List listaMeter = rootElement.getChildren("Meter");
        System.out.println("Leyendo XML Contadores...");
        for(int i=0;i<listaMeter.size();i++){
            //Se obtiene el elemento MeterNumber
            Element meterNumber = (Element) listaMeter.get(i);
            Element situation = (Element) listaMeter.get(i);
            Element baja = (Element) listaMeter.get(i);

            //Se comprueba que no esté dado de baja
            if(baja.getChildTextTrim("Baja").equals("0") && !meterNumber.getChildTextTrim("Situation").isEmpty()){
                //Ahora se guardan los datos en los String
                numSerie = meterNumber.getChildTextTrim("MeterNumber");
                calle = situation.getChildTextTrim("Situation");

                //Ahora se meten en el HashTable
                contadores.put(numSerie, calle);
            }
        }

Well from the verification, to add the key, value to the HashTable I enter contadores.put(numSerie,calle );

Afterwards to verify that the HashTable has been filled, all I do is go through it:

Enumeration e = contadores.keys();
        Object clave;
        Object valor;
        while(e.hasMoreElements()){
            clave = e.nextElement();
            valor = contadores.get(clave);
            System.out.println(clave+"-"+valor);//Mostramos la información
        }

I hope my contribution will help you. I do not do a get (i), and I get the same values. There are many ways to pick up an object from a Collection , and this is another way.

A greeting.

    
answered by 16.03.2017 в 12:03
0

I think my solution is simpler. If you need two values to be related in some way and save them in a collection in memory, the best thing is that you create a class with two properties that represent the two values you want to store and then use the collection that best suits your process ( lists, maps, batteries ...).

I think this is simpler, you can implement it with very little code, and it will be more readable.

I hope it serves you.

    
answered by 16.03.2017 в 12:23