简体   繁体   中英

cast LinkedHashMap to HashMap in groovy

How do I convert LinkedHashMap to java.util.HashMap in 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 = ...

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 .

LinkedHashMap is a subclass of HashMap so you can use it as a 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. The fact that it implements the Map interface should be sufficient for almost any purpose.

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.

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 ;--)

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...

 HashMap h = new HashMap() 
 h.getClass().getName();

works. Using the [:] notation seems to tie it to LinkedHashMap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM