java 在 groovy 中将 LinkedHashMap 转换为 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3780949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cast LinkedHashMap to HashMap in groovy
提问by user140736
How do I convert LinkedHashMap
to java.util.HashMap
in groovy?
我如何转换LinkedHashMap
为java.util.HashMap
groovy?
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
。
回答by Colin Hebert
LinkedHashMap
is a subclass of HashMap
so you can use it as a HashMap
.
LinkedHashMap
是 的子类,HashMap
因此您可以将其用作HashMap
.
Resources :
资源 :
回答by conleym
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. The fact that it implements the Map interface should be sufficient for almost any purpose.
但真正的问题是,你为什么关心底层实现是什么?你甚至不应该关心它是一个 HashMap。它实现了 Map 接口这一事实应该足以满足几乎任何目的。
回答by virtualeyes
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 (e.g. map.a.b.c), 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.
解决方法是将变量键包装在括号而不是引号中。
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 专家免于暂时的疯狂……
回答by hvgotcodes
HashMap h = new HashMap()
h.getClass().getName();
works. Using the [:] notation seems to tie it to LinkedHashMap.
作品。使用 [:] 符号似乎将它与 LinkedHashMap 联系起来。