Search code examples
javajsparraylistreverse

Reverse ArrayList on link


I have an ArrayList which consist of custom made objects called "History". When I click a link, the one called "Deposit1" at the top of my code example, I display the list in correct order.

However, I want to be able to reverse the list when the user click on the link "Deposit2" inside the table which is only displayed after the users click on the first link, "Deposit1".

Right now nothing happends, but I can system.out.print succesfully on secound link click.

Is there anyway to do this?

Note that code example is trimmed for better overview.

ArrayList <history> history = historyDAO.getHistory(x, y);



<li>
     <a href="history.jsp?Dep1=valueOfDep">Deposit1</a>
</li>

String sortDep1 = request.getParameter("Dep1"); 
String sortDep2 = request.getParameter("Dep2");

if (sortDep1 != null) {         
    
    <table class="table text">
      <tr>
        <th>Result</th>
        <th>Sport</th>
        <th>Deposit2<a href="history.jsp?Dep2=valueOfDep">Deposit2</a></th>
      </tr>

 if (sortDep2 != null) {
    Collections.reverse(history);
   }   


for (int i = 0; i < history.size() && i < list1.size(); i++) {
     
    <tr>
            <td><%=history.get(i).getRes()%></td>
            <td><%=history.get(i).getSport() %></td>
            <td><%=history.get(i).getDeposit()%></td>
    </tr>
  
<%}}%>

</tr>
</table>

Solution

  • You can pass 2 parameters in your href tag for both Dept1 & Dept2 so that sortDep1 is not null and it will go inside if-statement and depending on the value which is in url you can reverse your list. i.e :

    if (sortDep1 != null) {         
    <table class="table text">
    <tr>
       <th>Result</th>
       <th>Sport</th>
       //pass 2 parameter in url for dep1 & dep2
       <th>Deposit2<a href="history.jsp?Dep1=valueOfDep&Dep2=reverse">Deposit2</a></th>
    </tr>
    //check if not null and value is reverse
      if ((sortDep2 != null) && (sortDep2.equals("reverse")) {
        Collections.reverse(history);
        }   
     //other codes