Ameya
Ameya

Reputation: 549

accessing map values

Hi I have the following map called allLang[:] when I print out all the contents of the map using println allLang I get the following output:

[1:[en, de], 2:[en, de], 3:[en, de], 4:[en, de], 5:[en, de], 6:[en, de], 7:[en,
de], 8:[en], 9:[en], 10:[en, de], 11:[en, de], 12:[en, de], 13:[en, de], 14:[en,
 de], 15:[en], 16:[en], 17:[en], 18:[en], 19:[en], 27:[de], 33:[de], 34:[de], 35
:[de], 36:[de]]

however when I try to print out the value attached to a specific key for example:

println allLang[2] 

the output is null. I tried to access that value in multiple ways:

println allLang['2']
println allLang.get(2)
println allLang.get('2')

and neither of these work, I still get null.

Upvotes: 2

Views: 1964

Answers (1)

rdmueller
rdmueller

Reputation: 11012

How do you define the array? Could it be that the index is not '2' but ' 2' (or some other non printable character)?

the easiest way to find out is to...

  • println allLang.inspect()

this will give you a better output:

def allLang = [1:['en','de'],'2':['en','de'],3:['en','de']]
println allLang.inspect()

=> [1:["en", "de"], "2":["en", "de"], 3:["en", "de"]]
  • or you can iterate through the map and examine the keys:

    allLang.each {key, value -> println key.dump() }

    => <java.lang.Integer@1 value=1>

    => <java.lang.String@32 value=2 offset=0 count=1 hash=50>

    => <java.lang.Integer@3 value=3>

this should help you to find the right index....

Update: got it! The following code reproduces your problem:

def allLang = [:] 
def codes = ['en','de']
def query = [0:[id:0l],1:[id:1l],2:[id:2l],3:[id:3l],4:[id:4l]]; 
for(def i = 0; i < query.size(); i++){ 
  allLang[(query[i].id)] = codes; 
}
println allLang
println allLang[2]
println allLang['2']

The solution is, that the ´idused by hibernate is aLong`. So you have to access your map through long values:

println allLang[2l]

the best solution to avoid your problem is to avoid numerical indices:

allLang[''+(query[i].id)] = codes; 

will let you access your map through

println allLang['2']

Upvotes: 4

Related Questions