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 example: I add a potion to my inventory. Now I add ANOTHER potion but this time instead of adding ANOTHER potion to the inventory, it should instead show that I have: Potions x 2, while only taking up one spot in the ArrayList. I have come up with a few solutions but I feel as if they are bad practices. One solution I tried was to add an AMOUNT variable to the item itself and increment that. Help me find a much better solution?
EDIT: Ok please ignore the above. I have gotten pretty good answers for that but what surprised me was that there were almost no tutorials on role playing game inventory systems. I’ve done a lot of google searching and cannot find any good examples/tutorials/source code. If anyone could point me to some good examples/tutorials/source code (does not matter what language, but preferable java, or even c/c++) I would appreciate it, thanks. Oh, and any books on the subject matter.
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:To add something to the inventory you do
To remove something from the inventory you could for instance do
This can get messy if you do it in many places, so I would recommend you to encapsulate these methods in an
Inventoryclass.Good luck!