0

我有一个 Hashmap 对象allList,其形式为 type HashMap<String,ArrayList<Item>>。我想将它的 JSP 页面显示为jquery 手风琴。下面是我尝试过的代码。

<script type="text/javascript">
$(function() {
    $( "#accordion" ).accordion({
        heightStyle: "fill",
        collapsible: true
     });
});

</script>

<div id="accordion">
       <c:forEach items="${allList}" var="myLs">
    <h3>${myLs.key}</h3>
    <div>${myLs.value}</div> // This is giving me toString of Item.
</c:forEach>
</div>

我能够将哈希图的键显示为标题。但我无法弄清楚如何将相应的 arraylist 对象显示为有序列表。请帮帮我。

public class Item implements java.io.Serializable, Comparable<Object> {
    private Long id;
    private String itemName;
    private Double unitCost;
    private String status;
    private int quantity;
    public Item() {
    }
        //getters and setters
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Item)) {
            return false;
        }
        final Item item = (Item) o;
        if (getItemName() != null && item.getItemName() == null)
            return false;
        if (getItemName() == null && item.getItemName() != null)
            return false;
        if (!getItemName().equals(item.getItemName()))
            return false;
        return true;
    }
    public int hashCode() {
            return getItemName().hashCode();
    }

    public String toString() {
       return "Item - Id: "+getId+", Name : "+getItemName;
    }
    public int compareTo(Object o) {
       if (o instanceof Item) {
           return getItemName().compareTo(((Item) o).getItemName());
       }
       return 0;
    }
}
4

1 回答 1

3

您将使用第二个 forEach 循环:

<div id="accordion">
    <c:forEach items="${allList}" var="myLs">
        <h3>${myLs.key}</h3>
        <div>
            <c:forEach var="item" items="${myLs.value}">
                ${item.foo}, ${item.bar}  <br/>
            </c:forEach>
        </div>
    </c:forEach>
</div>

我认为您因错误的命名选择而感到困惑。您应该命名 a Map<String, ArrayList<Item>> allList,因为它不是列表,而是地图。而且您不应该命名地图条目myLs,因为它没有任何意义。我会将代码重构为(例如,假设地图中的键代表项目的所有者)

<div id="accordion">
    <c:forEach items="${itemsPerOwner}" var="itemsPerOwnerEntry">
        <h3>${itemsPerOwnerEntry.key}</h3>
        <div>
            <c:forEach var="item" items="${itemsPerOwnerEntry.value}">
                ${item.foo}, ${item.bar}  <br/>
            </c:forEach>
        </div>
    </c:forEach>
</div>
于 2013-01-10T12:47:23.957 回答