I have a Map keyed by Integer. Using EL, how can I access a value by its key?
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
I thought this would work but it doesn't (where map is already in the request's attributes):
<c:out value="${map[1]}"/>
Follow up: I tracked down the problem. Apparently ${name[1]}
does a map lookup with the number as a Long
. I figured this out when I changed HashMap
to TreeMap
and received the error:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
If I change my map to be:
Map<Long, String> map = new HashMap<Long, String>();
map.put(1L, "One");
then ${name[1]}
returns "One". What's with that? Why does <c:out>
treat a number as a long. Seems counterintuitive to me (as int is more commonly used than long).
So my new question is, is there a EL notation to access a map by an Integer
value?
Best Answer
Initial answer (EL 2.1, May 2009)
As mentioned in this java forum thread:
EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:
As a
Long
is never equal to anInteger
object, it does not find the entry in the map.That's it in a nutshell.
Update since May 2009 (EL 2.2)
Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:
That could be a good workaround here (also mentioned below in Tobias Liefke's answer)
Original answer:
EL uses the following wrappers:
JSP page demonstrating this: