限制 HashMap 接受特定字符串键

mee*_*rer 3 java hashmap

我们如何限制 HashMap 接受特定的字符串键。
这里的限制可以具有以下含义之一:
1.它可以抛出错误,或者
2.它可以简单地忽略具有该特定键的条目。

但条件是它应该在不重写putHashMap 方法的情况下实现,并且if在向给定映射添加条目时不使用条件。

假设我有一个 HashMap m并且我想限制特定的字符串键"myKey"。我想要的是,每当我们尝试添加任何带有键“myKey”的条目时,m 应该遵循上面提到的第 1 点或第 2 点。

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.
Run Code Online (Sandbox Code Playgroud)

我可以使用遗传学限制某种类型的键,但如何对单个给定的字符串键执行此操作。这是一个面试问题。

提前致谢 !!

sta*_*arf 5

您可以使用 emun 作为密钥。例如

public enum AllowedKey {
    KEY_ONE,
    KEY_TWO; // etc
}
Run Code Online (Sandbox Code Playgroud)

然后在你的地图中使用它:

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

如果您的实现允许,您也可以使用 EnumMap。

编辑: HashMap 的定义无法更改,因此这种方法不再适用。