Question

I'm trying to make a basic inventory system in java. The items that are all keys to a map and all extend the UsableItem class. For example, Tophat extends UsableItem. The problem is I can't save the myTophat item/object into it without making the key type Tophat, thereby not being able to store other types of items. How do I make my map to store everything that extends UsableItem?

Was it helpful?

Solution

You declare it this way:

Map<UsableItem, SomeObject> map;

Then you can add as keys whatever objects of type UsableItem or sub-types of it.

OTHER TIPS

You can use the powerful advantage of java generics "wildcards"

HashMap<? extends UsableItem, Integer>

Or

HashMap<T extends UsableItem, Integer>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top