I was writing code and I noticed some odd behavior in Groovy when I am dealing with XML and Maps. I thought about it and can't figure out why is it happening and should it that way.
I wrote sample code with 3 examples. Crucial difference between map1 & map3 is only on the following part:
Map1:
map1 << ["${it.name()}":it.value()]
Map3:
map3["${it.name()}"]=it.value()
Here is full code, you can copy-paste it into Groovy console:
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"]
The result that I am getting is following:
[head:[headHere], body:[bodyHere]]
null
[head:headHere, body:bodyHere]
headHere
[head:[headHere], body:[bodyHere]]
[headHere]
Even thou map1 and map3 look the same, the result of map["head"] is totally different, first gives null and second gives the actual result. I don't understand why is it happening. I spent some time on it and still don't get it. I used .getProperty()
to get info on a class, but it looks the same and feels the same on both maps and object inside. I tried couple more things and nothing gives me any idea on what is happening. I even tried different OS (Win XP, Mac OS) and still nothing.
I don't have any ideas anymore, please can one some explain odd behavior, why is it happening and what is the difference between map << [key:object]
and map[key] = object
?
Thank you.