Search code examples
jspjstlel

Access hash element by variable index


I'm refactoring 12 identical HTML form controls into a single piece of code inside a loop. I can't just loop the form because monthly values may or may not be present yet so I've built a month variable in the 1-12 range (so far so good):

<c:forEach var="month" begin="1" end="12">
    Month #<c:out value="${month}"/>
</c:forEach>

Now I need to access items from two hashmaps:

HashMap<Long, String> amounts
HashMap<String, String> invalidFields

The old "static" syntax was:

<c:out value="${it.amounts[1]}"/>
<c:out value="${it.invalidFields.amount_1}"/>

What's the syntax to inject month into the mix?


Solution

  • The begin and end of <c:forEach> are interpreted as java.lang.Integer, but your map keys are created as java.lang.Long.

    Integer int1 = new Integer(1);
    Long long1 = new Long(1L);
    System.out.println(int1.equals(long1)); // false
    

    So the Map#get() will never work for these keys.

    Fix your amounts to be Map<Integer, String> instead, or use a List<String> instead.

    Either way, then you can use:

    ${it.amounts[month]}