Separate objects in an ArrayList

This is the constructor of your class.

It is called whenever you write: new Tegenstander();
first you “declare” that there is a variable or an object, giving it a name and telling the application what kind of “thing” it is.

int a; says: “I name a variable ‘a’ and it holds an integer”
Tegenstander anyNameYouWant, does the same, only that its type is that of the class you wrote yourself.

it is executed once, in the beginning. that’s what makes this particular object come alive and be actually usable to you. that’s what is usually called an ‘instance’ of a class.

After trying what you suggested I got an error when I typed this line in processing because “someName” isn’t an array.

int a = someName[n].getX();

I just wanted to use a different name than yours, to point out that it could be any.
now you have a little confusion in your code…

  1. make an ArrayList → its name is ‘tegenstanders’ → you declare (!) your intention
  2. instantiate that ArrayList → tegenstander = new ArrayList<Tegen… → you create an actual object (the array list)
  3. tegenstanders.add(new Tegenstander()) → you create the actual object and add it to the list

You don’t need a ‘someName’ object, what you actually do is happening later when you use:

Tegenstander t = tegenstanders.get(i);

here you name a new object ‘t’.

so you have to use that name:
int a = t.getX();
(haha and yes, I was a little sloppy there, if the variable is a float, the method must return one too. so it should be 'float getX() {…)

as far as I am concerned, I don’t like ArrayLists, because you have to tease out the objects inside to use them.
So you make an Arraylist, add objects to them and so on.
Later you have to get each object from that list and shove it into another one.

for (int i = tegenstanders.size() - 1; i >= 0; i–) {
Tegenstander t = tegenstanders.get(i);
t.update();
t.getX();
t.getY();
}

Of course its an advantage to not have to know how large the list will be.
But I prefer to work with arrays…

for (int i = tegenstanders.size() - 1; i >= 0; i–) {
t[i].update();
t[i].getX();
t[i].getY();
}

but that’s just a personal flaw of mine :slight_smile:

3 Likes