Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make arrays with own objects in Java in Android Studio.

I have a long piece of code that looks like this

Kwas a1 = new Kwas("Kwas Azotowy(V)", "HNO3");
// etc..
Kwas a17 = new Kwas("Kwas FluorkoWodorowy", "HF");

How can I write it as an Array? I tried something like

Kwas[] a = new Kwas[17] 

But it didn`t work.

My "Kwas" class looks like the following:

public class Kwas {
String name;
String formula;

public Kwas( String nazwa, String wzor)
{
    name = nazwa;
    formula = wzor;
}

void setName(String c)
{
name = c;
}
void setFormula(String c)
{
    formula = c;
}
public String getName()
{
    return name;
}
public String  getFormula() {return formula;}

}

like image 812
Jakub Lelek Avatar asked Dec 11 '25 14:12

Jakub Lelek


2 Answers

You can do this:

List<Kwas> list = new ArrayList<Kwas>();
list.add(a2);
like image 134
Mykhailo Voloshyn Avatar answered Dec 14 '25 04:12

Mykhailo Voloshyn


Just implement an ArrayList like this:

ArrayList<Kwas> newArray= new ArrayList<>();

And then:

newArray.add(a2);
newArray.add(a3);
newArray.add(a4);
newArray.add(a5);
newArray.add(a6);
newArray.add(a7);  
...
...

Then if you want to get an specific item just write something like this:

newArray.get(1).getName(); //for example
like image 37
Faustino Gagneten Avatar answered Dec 14 '25 02:12

Faustino Gagneten