加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

字典 – Groovy Map.get(key,default)会改变地图

发布时间:2020-12-14 16:23:29 所属栏目:大数据 来源:网络整理
导读:我有以下Groovy脚本: mymap = ['key': 'value']println mymapv = mymap.get('notexistkey','default')println vprintln mymap 当我运行它时,我得到以下控制台输出: [key:value]default[key:value,notexistkey:default] 我很惊讶,在调用mymap.get(‘notexis
我有以下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’)后,第二个参数是当给定键不存在时返回的默认值,键keyxistkey被添加到我称之为方法的地图上.为什么?这是预期的行为吗?我怎样才能防止这种突变?

解决方法

使用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通过DefaultGroovyMethods.get(map,key,default)添加了Map.get(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和final get调用之间没有同步.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读