Need Help About ArrayList of Sprites ?

Hi Friends,

How to use an ArrayList of Sprites?

I seem to be having problems with some sprites in my game. The number of them isn’t the same from level to level, so I have created an ArrayList of these sprites to get a variable number of them.

Now, simply for some testing purposes (I’m not yet at the point that I am going to program their behavior) I am trying to get one to move on a keypress. However, it keeps freezing the program, and I realized that you don’t access ArrayList members the same way that you do an Array.

I mean, if it were an Array, it would be no problem to make one move with

array[i].move();

However, when calling the same function from an ArrayList,

arraylist.get(i).move();

I’m actually creating another intstance of that sprite. Which is what I believe it the source of the problem.

So, how can I get a member of an ArrayList to do something, without copying said member?

Thanks,
Jay

Those two bits of code should be identical, ArrayList is not creating another instance of your sprite unless your move() is doing something very weird. You’re going to have to explain your problem better and/or post more code.

Also, what does this have to do with networking? ???

I change this slightly arraylist.get(i).move();

becomes:

(Actor)arrayList.get(i).move();

dont you have to put what it should become in () at the front of it?

I get compiler errors if I dont.

Only if your not using generics.

When you use Java 1.5 you can use generics like:


ArrayList<Actor> actors = new ArrayList<Actor>();
[...]
for (Actor currentActor : actors) {
   currentActor.move();
}

When you don’t use generics it should be:

ArrayList actors = new ArrayList();
[...]
for (int i = 0; i < actors.size(); i += 1) {
   ((Actor) actors.get(i)).move();
}

Anyway, actors.get() doesn’t create a new Actor, it’s just a reference to your Actor object.