Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Avoid 'instanceof' when adding, or removing elements from list

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);
    }
}
like image 782
Pat K Avatar asked Dec 21 '22 10:12

Pat K


1 Answers

Use overloaded methods:

void addObject(Room room) {
  roomsOnMap.add(room);
}

void addObject(Item item) {
  itemsOnMap.add(item);
}

..
like image 114
Jack Avatar answered May 03 '23 23:05

Jack