문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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

HashMap<? extends UsableItem, Integer>

Or

HashMap<T extends UsableItem, Integer>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top