Hi all,
I'm currently designing the core for a personal game project of mine and seem to have got stuck with the simplist of problems.
[size=12pt]
The background[/size]
I have three classes
all of which extend the
Animal class.
There are only two other classes to consider:
House which extends
Building.
[size=12pt]
Class structures[/size]
Animal1 2 3 4 5 6 7 8 9 10 11
| public abstract class Animal {
public int x,y,qty;
public Animal(int x, int y, int qty) { this.x = x; this.y = y; this.qty = qty; }
} |
Mouse1 2 3 4 5 6 7 8 9
| public class Mouse extends Animal {
public static final int ID = 1;
public Mouse(int x, int y, int qty) { super(x,y,qty); }
} |
Building1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public abstract class Building {
Animal[] pets; ArrayList pets; HashMap pets;
public Building() { pets = new Animal[2]; pets = new ArrayList(); pets = new HashMap(); }
} |
House1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class House extends Building {
public static final int ID = 1;
public House() { super(); pets = new Animal[]{new Mouse(getX(), getY(), 1)}; pets.add(new Mouse(getX(), getY(), 1)); pets.put(new Integer(Mouse.ID), new Integer(1)); }
} |
[size=12pt]
The problem[/size]
Seen in the Building and House classes are three options for ways to save your pet objects into the house. At any point though, another mouse could come into the house, bumping up the qty variable value by one of the mouse object. My question is how do I do this efficiently and what is the best method to use?
i.e. Using arrays - If a mouse enters the house, I first need to run through the pets array attempting to cast each element to a Mouse, upon success, the qty value is incremented, but using the instanceof or casting seems very inefficient.
Using ArrayLists - nice to use, but I can't seem to find a nice way to pull individual animals out of the list when "building.getPet(id animalID)" is called.
Using HashMap - Each animal type has it's own unique ID - this ID is fed into the key of the hashMap and the value associated with this is the qty variable. My problem with this is that I would no longer have access to any of the animal's other variables, methods... If I were to use pets.put(new Mouse(x,y,z,1), new Integer(1)) this would duplicate the qty variable. :/
Ideally i'd like to use the unique static IDs as a lookup table to the actual class. So I think I'd use
1 2
| pets.put(new Integer(Mouse.ID), new Mouse(x,y,z,1)); |
Generally, there won't be more than 20 different type of animal in a building (the norm will be around 3). What would be the most efficient method to use?
Many thanks. Any advice would be much appreciated!
ribot