getting Object3D properties from a class/array

Started by dutch_delight, June 18, 2011, 04:40:44 PM

Previous topic - Next topic

dutch_delight

Hi all,

I'm stuck at something that probably isnt for this forum but not sure how to google this problem.
Bear in mind I'm still a Java amateur so that doesnt help.

I've got an Object3D array like this that gets pre-loaded on startup so it's got several different objects/classes in there.

private List<Object3D> WorldEnemies = new ArrayList<Object3D>();


Then I loop through my list:

int tp = 0;
int end = WorldEnemies.size();

for (int i = 0; i < end; i++) {

Object3D Object = WorldEnemies.get(tp);
int WayPoint =  Object.GetWayPoint ();
tp++;
}


But the problem is getting the WayPoint from the class. Eclipse wants to Cast the object to a certain type like so:
int WayPoint =  ((msam) object).GetWayPoint();
But that doesnt really work. It's not really giving an error message, the game just slows to a crawl.
(msam is an object that has Getwaypoint defined but there will be different objects with the same function later)
Getwaypoint returns an int from the class.

Is there a way to make the WayPoint a part of the Object3D so I always have access to it no matter the object type?
Or could I store the object type in a separate array and do an if/then?



oh i'm developing for android btw but this is more a java question i think.

Thanks for any advice

EgonOlsen

If you are having different classes that should have the same methods like getWayPoint() (btw.: consider to use Java's naming conventions, i.e. methods and variables start lower case, Classes upper case etc. It'll make the code easier to read), you can either implement an interface or extend a common base class which itself extends Object3D. In either case, your list can be of that type and doesn't have to be of Object3D.

For example:


public interface Moveable {
     int getWayPoint();
}

public class Enemy extends Object3D implements Moveable {
      int getWayPoint() {
      ..... // some implementation for enemies
      }
}

public class Rabbit extends Object3D implements Moveable {
      int getWayPoint() {
      ..... // some implementation for rabbits
      }
}

...
List<Moveable> worldStuff = new ArrayList<Moveable>();

...


That way, you don't have to cast. However, you can also do the way you've posted, i.e.


List<Object3D> worldStuff = new ArrayList<Object3D>();

for (Object3D obj:worldStuff) {
    Moveable mv=(Moveable) obj;
    int wayPoint=mv.getWayPoint();
}


The cast is cheap. It can't be responsible for the slow down. Maybe the slow down happens, because you are doing something expensive in getWayPoint() or with the returned way point. But the cast itself can't be responsible for it.