Cast LinkedHashMap in HashMap in groovy

How to convert LinkedHashMap to java.util.HashMap to groovy?

When I create something like this in groovy, it automatically creates a LinkedHashMap , even when I declare it as HashMap h = .... or def HashMap h = ...

I tried to do:

 HashMap h = ["key1":["val1", "val2"], "key2":["val3"]] 

and

 def HashMap h = ["key1":["val1", "val2"], "key2":["val3"]] 

h.getClass().getName() is still returning with LinkedHashMap .

+4
source share
4 answers

LinkedHashMap is a subclass of HashMap , so you can use it as a HashMap .


Resources:

+4
source

The simple answer is that cards have something similar to a copy constructor:

 Map m = ['foo' : 'bar', 'baz' : 'quux']; HashMap h = new HashMap(m); 

So, if you are attached to literal notation, but you absolutely must have a different implementation, this will do the job.

But the real question is: why do you care what a basic implementation is? You don’t even have to worry about it being a HashMap. The fact that it implements the map interface should be sufficient for any purpose.

+3
source
  HashMap h = new HashMap() h.getClass().getName(); 

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

+1
source

He was probably caught with the terrible Groovy-Map-Gocha, and he stumbled in the desert of opportunity, as I did all day.

Here's the deal:

When using variable string keys, you cannot access the map in the format of the notation notation (for example, map.abc), something unexpected in Groovy, where everything as a whole is short and wonderful; -)

The workaround is to wrap the 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 such a map will bring great pleasure to sadists around the world:

 Map m = ["$a":["$b":["$c":1]]] 

Hope this saves another Groovy -ist from temporary insanity ...

+1
source

All Articles