gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:24:56 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com