Create and manipulate multidimensional associative array

4

How can I create a multidimensional associative array in Java? Something similar to this:

Array = {
    "carro 1" : Array {
        "portas" : 5,
        "cor" : "preto",
        "km" : 10670
    },
    "carro 2" : Array {
        "portas" : 3,
        "cor" : "vermelho",
        "km" : 70334
    },
}

And how can I later iterate with a for and read each element? I even found this class Map but I did not understand how I can use it for the purpose I'm looking for.

    
asked by anonymous 12.01.2015 / 15:22

1 answer

4

If the idea is to have a list of Cars it is easier to create a Car or Vehicle object with the attributes you need, for example:

class Carro
{
   private String nome;
   private int portas;
   private String cor;
   private int km;

   Carro (String nome, int portas, String cor, int km)
   {
      this.nome   = nome;
      this.portas = portas;
      this.cor    = cor;
      this.km     = km;
   }
   public String getNome () { return nome;   }
   public int getPortas  () { return portas; }
   public String getCor  () { return cor;    }
   public int getKm      () { return km;     }

   public void setNome   ( int nome   ) { this.nome   = nome;   }
   public void setPortas ( int portas ) { this.portas = portas; }
   public void setCor    ( String cor ) { this.cor    = cor;    }
   public void setKm     ( int km     ) { this.km     = km;     }

   //Restantes métodos como clone, equals, compareTo, toString, etc..
}

You can use ArrayList<value> to put the cars in a list.

Carro carro = new Carro ("carro 1", 3, "preto", 120000);

ArrayList<Carro> listaDeCarros = new ArrayList<Carro>();
listaDeCarros.add(carro);

// Para percorrer o ArrayList:

for (Carro carro_temp : listaDeCarros) 
{
    Log.e("carros", "" + carro_temp.getNome());
}

Or you can use Map<key,value> which has each key associated with a value. The key (key) can be a code or a name (of the car) and the value can be the object itself.

Carro carro2 = new Carro ("carro 2", 5, "verde", 143122);

Map<String, Carro> mapDeCarros = new Map<String, Carro>();
mapDeCarros.put(carro.getNome(), carro);

// Para percorrer o Map:

for (Map.Entry<String, Carro> entry : mapDeCarros.entrySet())
{
    Log.e("carros", "" + entry.getKey() + "/" + entry.getValue().toString());
    //                   nome/carro
}

Example on Ideone

    
12.01.2015 / 15:38