Groovy中Map的奇怪行为

MeI*_*eIr 4 groovy

我正在编写代码,当我处理XML和Maps时,我注意到Groovy中有一些奇怪的行为.我想到了它,无法弄清楚为什么会这样,应该这样.

我用3个例子编写了示例代码.map1和map3之间的关键区别仅在于以下部分:

地图1:

map1 << ["${it.name()}":it.value()]
Run Code Online (Sandbox Code Playgroud)

MAP3:

map3["${it.name()}"]=it.value()
Run Code Online (Sandbox Code Playgroud)

这是完整的代码,您可以将其复制粘贴到Groovy控制台:

def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>'


Map map1 = [:]

def node = new XmlParser().parseText(xml) 

node.each {
      map1 << ["${it.name()}": it.value()]
} 

println map1
println map1["head"]

println ">>>>>>>>>>>>>>>>>>>>>>"



Map map2 = [:]

map2 << ["head":"headHere"]
map2 << ["body":"bodyHere"]

println map2
println map2["head"]

println "<<<<<<<<<<<<<<<<<<<<<<"



def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>'    

Map map3 = [:]

def node2 = new XmlParser().parseText(xml2) 

node2.each {
      map3["${it.name()}"]=it.value()
} 

println map3
println map3["head"]
Run Code Online (Sandbox Code Playgroud)

我得到的结果如下:

[head:[headHere], body:[bodyHere]]
null

[head:headHere, body:bodyHere]
headHere

[head:[headHere], body:[bodyHere]]
[headHere]
Run Code Online (Sandbox Code Playgroud)

即使map1和map3看起来相同,map ["head"]的结果也完全不同,首先给出null,然后给出实际结果.我不明白为什么会这样.我花了一些时间在它上面仍然没有得到它.我曾经.getProperty()在一个类上获取信息,但它看起来一样,并且在地图和对象里面感觉相同.我尝试了更多的东西,没有什么能让我知道发生了什么.我甚至尝试了不同的操作系统(Win XP,Mac OS),但仍然没有.

我没有任何想法了,可以请一些一个解释奇怪的行为,为什么会发生,之间有什么区别map << [key:object]map[key] = object

谢谢.

Ove*_*ous 9

可能有用的一件事是,不要使用GStrings作为密钥.Groovy支持将对象直接用作键,将它们包装在括号中.

手册:

默认情况下,映射键是字符串:[a:1]等同于["a":1].但是如果你真的想要一个变量成为关键,你必须将它包装在括号中:[(a):1].

完全工作的例子:

def xml = '<xml><head>headHere</head><body>bodyHere</body></xml>'

Map map1 = [:]
def node = new XmlParser().parseText(xml)
node.each {
    map1 << [ (it.name()): it.value() ]
}

println map1
println map1["head"]
println ">>>>>>>>>>>>>>>>>>>>>>"

Map map2 = [:]

map2 << ["head":"headHere"]
map2 << ["body":"bodyHere"]

println map2
println map2["head"]

println "<<<<<<<<<<<<<<<<<<<<<<"

def xml2 = '<xml><head>headHere</head><body>bodyHere</body></xml>'

Map map3 = [:]

def node2 = new XmlParser().parseText(xml2)

node2.each {
    map3[it.name()] = it.value()
}

println map3
println map3["head"]
Run Code Online (Sandbox Code Playgroud)

输出是:

[head:[headHere], body:[bodyHere]]
[headHere]
>>>>>>>>>>>>>>>>>>>>>>
[head:headHere, body:bodyHere]
headHere
<<<<<<<<<<<<<<<<<<<<<<
[head:[headHere], body:[bodyHere]]
[headHere]
Run Code Online (Sandbox Code Playgroud)