Simple question, yet I couldn’t figure out the answer,
Is it possible to constraint key convention for my application’s HashMap? As I don’t want future developer who works on it and try to use different key, I want to enforce a rule regarding what type of key they have to use.
As an example :
There can be only 4 pair,
And all four key can only be,
1. <North, Place>
2. <South, Place>
3. <East, Place>
4. <West, Place>
When developer use my methods they should get error if they use different key other than above mentioned.
Thank you for any kind of help
What I can do so far :
I might check by an if statement while adding key and value into
HashMap, lets say in setLocationList(String key, Place place);. But I
want something smarter than this if it is available. Thanks.
Sure, use an enum for your directions, then use an
EnumMapfor your map type.This guarantees that the key must be of type
Direction. And it’s watertight—because of the type key passed to theEnumMapconstructor, even if you’re using generics-blind code, the type restriction will still get enforced (at runtime).