Jakub Lelek
Jakub Lelek

Reputation: 27

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;}

}

Upvotes: 1

Views: 7150

Answers (5)

Moshe Edri
Moshe Edri

Reputation: 244

ArrayList<yourObjectName> arrayName = new ArrayList<yourObjectName>();

Then .add(object) on every object

Upvotes: 1

JasperHsu
JasperHsu

Reputation: 45

You can simply type:

ArrayList<ObjectType> arrayName = new ArrayList<ObjectType>();

Adding Elements:

arrayName.add(someObject);

Removing Elements:

arrayName.remove(arrayName.get(someInteger));

Getting Elements:

arrayName.get(someInteger);

PS: Don't forget to import:

import java.util.ArrayList;

Upvotes: 0

MrZarq
MrZarq

Reputation: 258

I can't comment yet, so I have to provide it as an answer. Everyone is answering here how OP can construct a List, but no one is actually answering how he can create an array, which is probably very confusing for OP who might now think you can't create arrays of self-defined objects. You definitely can. But I don't know what the problem is.

Kwas[] a1 = new Kwas[17];

is definitely the right syntax. Are you sure you include the class? Can you post the exact code and error?

My guess is that you didn't import your class. In Android Studio, try placing your cursor after Kwas and pressing Ctrl+Space. This should show a dropdown list. Select the first line and press enter. Now it should have added an import to your class.

Upvotes: 1

Faustino Gagneten
Faustino Gagneten

Reputation: 2774

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

Upvotes: 3

Mykhailo Voloshyn
Mykhailo Voloshyn

Reputation: 594

You can do this:

List<Kwas> list = new ArrayList<Kwas>();
list.add(a2);

Upvotes: 5

Related Questions