[英]cast LinkedHashMap to HashMap in groovy
How do I convert LinkedHashMap
to java.util.HashMap
in groovy? 如何在groovy中将LinkedHashMap
转换为java.util.HashMap
?
When I create something like this in groovy, it automatically creates a LinkedHashMap
even when I declare it like HashMap h = ....
or def HashMap h = ...
当我在groovy中创建这样的东西时,它会自动创建一个LinkedHashMap
即使我声明它像HashMap h = ....
或def HashMap h = ...
I tried doing: 我试过做:
HashMap h = ["key1":["val1", "val2"], "key2":["val3"]]
and 和
def HashMap h = ["key1":["val1", "val2"], "key2":["val3"]]
h.getClass().getName()
still comes back with LinkedHashMap
. h.getClass().getName()
仍然返回LinkedHashMap
。
LinkedHashMap
is a subclass of HashMap
so you can use it as a HashMap
. LinkedHashMap
是HashMap
的子类,因此您可以将其用作HashMap
。
Resources : 资源:
Simple answer -- maps have something that looks a lot like a copy constructor: 简单的答案 - 地图有一些看起来很像复制构造函数:
Map m = ['foo' : 'bar', 'baz' : 'quux'];
HashMap h = new HashMap(m);
So, if you're wedded to the literal notation but you absolutely have to have a different implementation, this will do the job. 所以,如果你坚持使用文字符号,但你必须有一个不同的实现,这将完成这项工作。
But the real question is, why do you care what the underlying implementation is? 但真正的问题是,为什么你关心底层实现是什么? You shouldn't even care that it's a HashMap. 你甚至不应该关心它是一个HashMap。 The fact that it implements the Map interface should be sufficient for almost any purpose. 它实现Map接口的事实应该足以满足任何目的。
He probably got caught with the dreaded Groovy-Map-Gotcha, and was stumbling around in the wilderness of possibilities as I did for the entire afternoon. 他可能被可怕的Groovy-Map-Gotcha抓住了,并且在整个下午的旷野中磕磕绊绊。
Here's the deal: 这是交易:
When using variable string keys, you cannot access a map in property notation format (eg map.abc), something unexpected in Groovy where everything is generally concise and wonderful ;--) 使用变量字符串键时,您无法以属性表示法格式访问地图(例如map.abc),这是Groovy中出乎意料的事情,其中一切都非常简洁和精彩; - )
The workaround is to wrap variable keys in parens instead of quotes. 解决方法是将变量键包装在parens而不是引号中。
def(a,b,c) = ['foo','bar','baz']
Map m = [(a):[(b):[(c):1]]]
println m."$a"."$b"."$c" // 1
println m.foo.bar.baz // also 1
Creating the map like so will bring great enjoyment to sadists worldwide: 像这样创建地图将为全世界的虐待狂带来极大的乐趣:
Map m = ["$a":["$b":["$c":1]]]
Hope this saves another Groovy-ist from temporary insanity... 希望这可以从临时疯狂中拯救另一个Groovy-ist ......
HashMap h = new HashMap()
h.getClass().getName();
works. 作品。 Using the [:] notation seems to tie it to LinkedHashMap. 使用[:]表示法似乎将它绑定到LinkedHashMap。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.