开发者

Constraint Specific Key - convention for HashMap - Java

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 EnumMap for your map type.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;
}

Map<Direction, Place> map = new EnumMap<Direction, Place>(Direction.class);

This guarantees that the key must be of type Direction. And it's watertight---because of the type key passed to the EnumMap constructor, even if you're using generics-blind code, the type restriction will still get enforced (at runtime).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜