views:

67

answers:

3

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.

+2  A: 

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


Resources :

Colin Hebert
I agree. I should not matter what implementation of a HashMap it uses.
sbglasius
+1  A: 
 HashMap h = new HashMap() 
 h.getClass().getName();

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

hvgotcodes
A: 

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.