I have a Map keyed by Integer. Using JSTL, 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 JSTL tag notation to access a map by an Integer
value?