Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Groovy map internal representation

I understand that groovy uses java.util.ArrayList to represent objects created using array literals like so: arr = []. I wanted to understand what underlying object groovy uses to create a map created like so: my_map = [:]. I wrote this code below:

 7 array = []
  8 array[1] = 'a'
  9 array[2] = 'b'
 10 println array.class.name
 11 println array
 12 
 13 my_map = [:]
 14 my_map['OK'] = 200
 15 println my_map.class
 16 println my_map

The output produced by code above is:

java.util.ArrayList
[null, a, b]
null
[OK:200]

Notice the .class attribute is missing on my_map. Why is this happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

my_map is a Map. In groovy map.key is a convenience to get the value associated with the key from the map.

The issue here is that it’s looking for a key named class, and there isn’t one.

To get the class of a Map, you need to explicitly ask for it with my_map.getClass()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading