If the idea is to have a list of Cars it’s 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 a ArrayList<value>
to put cars on 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 the Map<key,value>
that has each associated key a value. A key(key) can be a code or a name (of the car) and the value (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 in Ideone
I am now trying to put all the instances of my Object into one
ArrayList
as indicated but gives error. Sayscannot resolve symbol 'add'
and inside the add says that the car class is not recognized, I’m using your code without major changes– CIRCLE
As you can see here http://developer.android.com/reference/java/util/ArrayList.html#add%28E%29 there is an add method.
– Jorge B.
What IDE are you using? It’s what you need to do
import
of some libraries (the IDE usually does it alone)– Jorge B.
Using Android Studio with auto import, I know this method exists but for some reason is not being recognized in my code
– CIRCLE
How strange. It should work, I tested it here and it worked.
– Jorge B.
anyway I got a workarround using a
public static List<TableHelper> tableList = Arrays.asList(...);
, Thank you @Jorge– CIRCLE
There’s a bug in Ideone, it’s missing
e
in theLog.("carro"...)
– Gustavo Cinque
Check this one: http://ideone.com/ZlKKZb
– Jorge B.