首页 > 解决方案 > 如果值不同,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

我可以编写代码来做到这一点,但感觉可能已经有一个我不知道的很好的解决方案?

标签: java

解决方案


您可以使用containsKeyget函数来比较键和值的存在,如下所示:

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}

推荐阅读