java - 如果值不同,Java Map 将拒绝 put
问题描述
我想知道在地图上是否有一个很好的 a 或方法实现,如果条目已经存在并且放置的值与地图中已经存在的值不同Map
,它将拒绝(有一个例外) a ?put
这是一些说明我想要的代码
Map<String, String> map = new HashMap<>(); // Could be a different Map impl
// Init the map with some entries
map.put("key", "value");
map.put("anotherKey", "anotherValue");
map.put("key", "value"); // No issue as the value matches the existing
map.put("key", "differentValue"); // This should throw as we are attempting to change the value
因此,一旦添加,它将是一种具有不可变条目的映射。Map.put 上的 JavaDoc 建议这可以适合 Map 合同
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
我可以编写代码来做到这一点,但感觉可能已经有一个我不知道的很好的解决方案?
解决方案
您可以使用containsKey
和get
函数来比较键和值的存在,如下所示:
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("key", "value");
try {
addToMap(map, "key", "value");
addToMap(map, "anotherKey", "anotherValue");
addToMap(map, "key", "value");
addToMap(map, "key", "differentValue");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(map);
}
private static void addToMap(Map<String, String> map, String key, String value) throws Exception {
if(map.containsKey(key) && !map.get(key).equals(value))
throw new Exception("exception");
map.put(key, value);
}
输出:
java.lang.Exception: exception
at Main.addToMap(Main.java:25)
at Main.main(Main.java:15)
{anotherKey=anotherValue, key=value}
推荐阅读
- function - How can I import an external script from vue.js and use the functions contained in the external script?
- typescript - 打字稿,vue,无法运行笑话
- java - java中的泛型和方法
- java - 片段中的 findViewById 无法获取其视图(在空对象引用上)
- python - 正在打印两个列表
- elasticsearch - 如何在 Elasticsearch 中使用无痛脚本获取数组字段的匹配字段值?
- node.js - 将 unix 时间戳插入 postgres 时间戳列 (node-postgres)
- mongodb - 仅在 mongodb 中为动态字段名称项目嵌套对象
- postgresql - 如何将 Apollographql 连接到多个 Postgres 数据库
- javascript - 我的 javascript 代码不适用于工作 php 的结果