dictionary - Groovy Map.get(key, default) 改变 map

标签 dictionary groovy mutability

我有以下 Groovy 脚本:

mymap = ['key': 'value']
println mymap

v = mymap.get('notexistkey', 'default')

println v
println mymap

当我运行它时,我得到以下控制台输出:
[key:value]
default
[key:value, notexistkey:default]

我很惊讶在调用 mymap.get('notexistkey', 'default') 之后其中第二个参数是给定键不存在时返回的默认值,键notexistkey被添加到我调用该方法的 map 中。为什么?这是预期的行为吗?我怎样才能防止这种突变?

最佳答案

使用 Java 的 Map.getOrDefault(key, value) 反而:

mymap = ['key': 'value']
println mymap

v = mymap.getOrDefault('notexistingkey', 'default')

println v
println mymap

输出:
[key:value]
default
[key:value]

Groovy SDK 添加 Map.get(key, default)通过 DefaultGroovyMethods.get(map, key, default) 如果您看一下 Javadoc 所说的内容,您就会明白这种行为是预期的:

Looks up an item in a Map for the given key and returns the value - unless there is no entry for the given key in which case add the default value to the map and return that.



这就是这个方法的实现的样子:
/**
 * Looks up an item in a Map for the given key and returns the value - unless
 * there is no entry for the given key in which case add the default value
 * to the map and return that.
 * <pre class="groovyTestCase">def map=[:]
 * map.get("a", []) &lt;&lt; 5
 * assert map == [a:[5]]</pre>
 *
 * @param map          a Map
 * @param key          the key to lookup the value of
 * @param defaultValue the value to return and add to the map for this key if
 *                     there is no entry for the given key
 * @return the value of the given key or the default value, added to the map if the
 *         key did not exist
 * @since 1.0
 */
public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {
    if (!map.containsKey(key)) {
        map.put(key, defaultValue);
    }
    return map.get(key);
}

这是一个很老的概念(从 Groovy 1.0 开始)。但是我建议不要使用它 - 这个 .get(key, default)操作既不是原子的,也不是同步的。当您在 ConcurrentMap 上使用它时,问题就开始了它是为并发访问而设计的——这个方法违反了它的约定,因为 containsKey 之间没有同步。 , put最后 get称呼。

关于dictionary - Groovy Map.get(key, default) 改变 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48806509/

相关文章:

python - 在 Python 中更新可变变量时自动执行操作

reactjs - 如何将 React Modal 与 map 功能一起使用?

grails - Groovy 和 final 属性如何用 Map 设置?

jenkins - 在 Jenkins 开始另一项工作时如何获取内部错误消息

struct - 我怎样才能使某些结构字段可变?

vector - 无法通过索引访问向量中的可变引用

vector - 如何在迭代过程中改变向量的项?

python - 在 Python 中从大型字典中获取前 3 个最高值的快速有效方法是什么?

python - 在 Python 中遍历嵌套字典和子字典

java - 玩! 1.2.5。 : Object's collection of enums binding to template