I am using an ArrayList as my \"inventory\". I am having trouble figuring out a way to add multiples of the same item without taking up a spot in the \"inventory\". For exam
You're probably better off creating a class called InventorySlot
, with a quantity and contents field. This also give you the flexibility of adding other properties, such as what the inventory slot can contain, should you decide to create a 'potions' only sack or something like that.
Alternatively, a StackCount
and a boolean IsStackable
, or perhaps MaxStack
property is used in quite a few MMO's, it's a perfectly valid technique too.
Similar to aioobe's solution, you can use TObjectIntHashMap.
TObjectIntHashMap<Item> bag = new TObjectIntHashMap<Item>();
// to add `toAdd`
bag.adjustOrPutValue(item, toAdd, toAdd);
// to get the count.
int count = bag.get(item);
// to remove some
int count = bag.get(item);
if (count < toRemove) throw new IllegalStateException();
bag.adjustValue(item, -toRemove);
// to removeAll
int count = bag.remove(item);
You can create a multiples class.
class MultipleOf<T> {
int count;
final T t;
}
List bag = new ArrayList();
bag.add(new Sword());
bag.add(new MultipleOf(5, new Potion());
Or you can use a collection which records multiples by count.
e.g. a Bag
Bag bag = new HashBag() or TreeBag();
bag.add(new Sword());
bag.add(new Potion(), 5);
int count = bag.getCount(new Potion());
The usual way to solve this (using the standard API) is to use a Map<Item, Integer>
that maps an item to the number of of such items in the inventory.
To get the "amount" for a certain item, you then just call get
:
inventory.get(item)
To add something to the inventory you do
if (!inventory.containsKey(item))
inventory.put(item, 0);
inventory.put(item, inventory.get(item) + 1);
To remove something from the inventory you could for instance do
if (!inventory.containsKey(item))
throw new InventoryException("Can't remove something you don't have");
inventory.put(item, inventory.get(item) - 1);
if (inventory.get(item) == 0)
inventory.remove(item);
This can get messy if you do it in many places, so I would recommend you to encapsulate these methods in an Inventory
class.
Good luck!
or an class InventoryField with an item and an integer for the amount.
public class InventoryField{
int count;
Item item;
}
public class Inventory extends ArrayList<InventoryField>{
...
}
How about the following
public class Item{
int count;
String name;
}
Then have a list representing the inventory
public class Player {
List<Item> inventory = new ArrayLis<Item>();
}