字典 – Groovy Map.get(key,default)会改变地图
我有以下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通过
这就是这个方法的实现: /** * 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",[]) << 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调用之间没有同步. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |