Reputation: 248
Say I've got a Java file with 500 custom objects of type Item
. Now, say I want users to be able to add/remove any one of those objects to that list in the program. I want to try to avoid doing something like this:
public class Inventory {
public static ArrayList<Item> inv = new ArrayList<>();
public static void addItem1 {
inv.add(Item.Item1); //Pulling from Item class
} //addItem1()
public static void removeItem1 {
inv.remove(Item.Item1);
} //removeItem1()
public static void addItem 2 {
. . .
}
. . .
}
By doing that, I'd have to make an add and a remove function for every single item. There will be hundreds of items, so I sincerely hope there's a better way for the user to be able to do so from inside of the program. This would further be awful because of how it would require some massive nested switch
statements to swap out everything.
Instead I'd hope to implement a single adder method and a single remover method, that could take the user's input (a String with the literal name of the Item
they are trying to add), and somehow find/select the Item
. Implementation thoughts?
Upvotes: 0
Views: 94
Reputation: 151
How about using generic class ?
public class Inventory<T> {
public static ArrayList<Item> inv = new ArrayList<>();
public void addItem (T item){
inv.add((Item)item); // where item can be anything from Item.item1 to Item.item500
}
public void removeItem (T item){
inv.remove((Item)item);
}
In that case, to see if your item is in fact an item do something similar to this: System.out.println(item.getClass().getName()); //should return Item
Upvotes: 2
Reputation: 433
Perhaps use:
public void setItem(Item item){
inv.add(item);
}
Then use the same concept for removal.
Upvotes: 0