I'm creating a game. A game has a GameMap. In order to track state of things on the GameMap, I wanted to create ArrayLists for each of those things. The problem is, I don't want to have to create separate methods for adding, or removing items from each type of ArrayList. I'm a newb so of course the first thing I can think of is the 'instanceof' operator.
Keep in mind that, at present, GameMap is a discrete class, and not an interface, or abstract class. The intent is to instantiate a GameMap object when the game is initialized.
public class GameMap {
//GameMap has a name
private String mapName;
//GameMap has rooms
private ArrayList<Room> roomsOnMap;
//GameMap has items
private ArrayList<Item> itemsOnMap;
//GameMap has people
private ArrayList<Person> peopleOnMap;
//construct GameMap with rooms, items, and people
private GameMap(String mapName, ArrayList someRooms, ArrayList someItems, ArrayList somePeople)
{
this.mapName = mapName;
this.roomsOnMap = someRooms;
this.itemsOnMap = someItems;
this.peopleOnMap = somePeople;
}
public void addObject(Object o)
{
//HOW DO I AVOID THIS?
if(o instanceof Room)
{
roomsOnMap.add((Room) o);
}
else if(o instanceof Item)
{
itemsOnMap.add((Item) o);
}
else if(o instanceof Person)
{
peopleOnMap.add((Person) o);
}
}
Use overloaded methods:
void addObject(Room room) {
roomsOnMap.add(room);
}
void addObject(Item item) {
itemsOnMap.add(item);
}
..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With