7

In a backing bean I have defined a Map<Integer,String> property. When trying to access the map from EL inside an xhtml-file, I get nothing back.

<h:outputLabel value="#{bean.myMap[0]}">

does not return the value for key 0. With a String key it works.

It works with a List<String>, but I want the Map to have some kind of sparse array (not all indexes have values)

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Björn Landmesser
  • 953
  • 10
  • 26

2 Answers2

8

EL interprets your literal number 0 as long type. Try a Map<Long,String> instead of Map<Integer,String>.

This is what you are supposedly doing :

myMap.put(Integer.valueOf(0), "SomeValue"); 

This is what EL does to get back the value :

String value = myMap.get(Long.valueOf(0));
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
3

I had the same problem and found this when I was googling for a solution. Changing the map wasn't really an option for me, since it was auto-generated code, so here's what I ended up doing.

I created a managed bean:

package my.bean.tool;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;

@ManagedBean
@ApplicationScoped
public class Caster {

    public Caster() {
    }

    public int toInt(long l) {
        return (int) l;
    }
}

Then I simply did what in your case would have been:

<h:outputLabel value="#{bean.myMap.get(caster.toInt(0))}">
Bjørn Stenfeldt
  • 1,432
  • 1
  • 18
  • 25