【发布时间】:2016-08-25 12:18:01
【问题描述】:
使用以下 sn-p 我无法从地图中检索 gString:
def contents = "contents"
def gString = "$contents"
def map = [(gString): true]
assert map.size() == 1 // Passes
assert gString.hashCode() == map.keySet().first().hashCode() // Passes, same hash code
assert gString.is(map.keySet().first()) // Passes, exactly the same object
assert map[gString] // Fails
怎么可能?
这里有趣的是map.get(map.keySet()[0]) 可以正常工作,而map.get[map.keySet()[0]] 不能。
断言消息清楚地表明有问题:
assert map[gString] // Fails
| ||
| |contents
| null
[contents:true]
这和Why groovy does not see some values in dictionary?不是同一个问题 那里的第一个答案表明:
您将 GString 实例作为键添加到地图中,然后使用 String 实例搜索它们。
在这个问题中,我明确添加了GString 并尝试检索GString。
Why are there different behaviors for the ways of addressing GString keys in maps? 和 Groovy different results on using equals() and == on a GStringImpl 也没有给我答案。我不会改变任何东西,也不会将String 与GString 混合在一起。 Groovy documentation 也无济于事。
【问题讨论】:
-
非常好的问题,也许您应该在票证中添加
map.get[map.keySet()[0]]不起作用,但map.get(map.keySet()[0])工作正常。 -
@Vampire 谢谢,编辑过的问题——确实很有趣
-
只需添加
map[gString] = 1;即可生成这张有趣的地图[contents:true, contents:1]。几乎就像getAt/putAt使用 gStrings 的字符串表示... -
请在此处查看我的 cmets 关于您的(错误排除的)问题:stackoverflow.com/questions/39141245/…。您似乎发现了一个合法的错误。 Groovy 运行时似乎将
map[gString]动态映射到DefaultGroovyMethods.getAt()的错误重载。
标签: dictionary groovy gstring