sshekhar
sshekhar

Reputation: 147

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?

Upvotes: 1

Views: 87

Answers (1)

tim_yates
tim_yates

Reputation: 171054

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

Upvotes: 2

Related Questions