Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 489
TeaCupApp Avatar asked Dec 31 '25 11:12

TeaCupApp


1 Answers

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).

like image 166
Chris Jester-Young Avatar answered Jan 03 '26 00:01

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!