Constrain HashMap to accept a specific string key

How can we restrict the use of the HashMap to a specific string key.
The constraint here can have one of the following values:
1. It can throw an error, or
2. It can simply ignore this entry, which has this particular key.

But the condition is that it must be implemented without overriding the put

HashMap method and without using the condition if

when adding an entry to this map.

Suppose I have a HashMap m and I want to constrain a specific string key "myKey" . I want, whenever we try to add any entry with the key "myKey", m should be followed by point 1 or point 2 as above.

m.put("otherKey", "value"); // should add to the map<br/>
m.put("myKey","value"); // Either throw an error or ignore this entry and should not add to the map.

      

I can restrict the type of keys using Genetics, but how do I do this for one given string key. It was an interview question.

Thanks in Advance !!

+3


source to share


5 answers


These are very strange restrictions that you have ... but here it is without operator if

or override:



void addToMap(HashMap<String,Sting> map, String key, String value) {
    switch (key) {
        case "MyKey":
             throw new IllegalArgumentException(key);
        default: map.put(key, value);
    }
}

      

+3


source


You can do any number of tricks to avoid explicit input if

. The existing answer using switch

, works like using a loop while

, and is aborted or returned unconditionally within it. If your interviewer really wants to see how you can write nasty code, that's your answer.

If you are interested in real-world ways to limit keys HashMap

, you should use Guava ForwardingMap

and extend it .put*()

and .putAll()

throw away IllegalArgumentException

" if some property of the specified key or value does not allow it to be stored in this map ." Even if you are not using Guava, you should prefer the decorator pattern over extension HashMap

directly (Effective Java: Point 16).



Also, you might find it easier to use a dedicated type for your keys, eg. a RestrictedString

that performs your sanitation. You can then create Map<RestrictedString, String>

and trust that there are only valid keys on the card. This avoids using conditional ( if

/ switch

etc.) Code by Map

moving it into a class instead RestrictedString

.

Even if the interviewer asks a puzzle question that answers with real solutions (while still acknowledging their positions), you can only score with any legitimate employer.

+2


source


You can use emun as a key. For example,

public enum AllowedKey {
    KEY_ONE,
    KEY_TWO; // etc
}

      

Then use this on your map:

Map<AllowedKey, String> map = new HashMap<>();
map.put("string", "value"); // compile error!
map.put(AllowedKey.KEY_ONE, "value"); // success!

      

You can also use EnumMap if you can implement it.

Edit: The definition of the HashMap cannot be changed, so this approach is no longer applicable.

+2


source


Use Set to store forbidden keys.

Then display true and false within the map:

Set prohibitedKeys = new HashSet<String>();
prohibitedKeys.add("myKey");
Map<Boolean,Map<String,String>> boolMap = new HashMap<Boolean,Map<String,String>>();
Map<String,String> myMap = new HashMap<String,String>();

boolMap.put(Boolean.FALSE,myMap);
//This will work
Map m = boolMap.get((Boolean)prohibitedKeys.contains("otherKey"))
m.put("otherKey", "value");

//This will throw an null pointer exception
m.put("myKey", "value");

      

+1


source


EnumMap will allow you to restrict keys to a static subset, but will obviously violate the requirement Map<String, String>

.

With a decorator, the decorator and decorated class usually use an interface, i.e. a map, so implementing a custom one put(k, v)

and passing all other methods through a decorated HashMap might be acceptable as put(k, v)

long as you are not overriding the HashMap method.

The only other solution I can think of is to use an AOP based solution to apply the before advice for the put (k, v) method and reject any invalid values.

0


source







All Articles