开发者

How we get the List objects in backward direction?

开发者 https://www.devze.com 2023-02-02 13:35 出处:网络
Hi i am getting List object that contains pojo class objects of the table. in my case i have to show the table da开发者_运维技巧ta in reverse order. mean that, for ex

Hi i am getting List object that contains pojo class objects of the table. in my case i have to show the table da开发者_运维技巧ta in reverse order. mean that, for ex i am adding some rows to particular table in database when i am added recently, the data is storing at last row in table(in database). here i have to show whole content of the table in my jsp page in reverse order, mean that what i inserted recently have to display first row in my jsp page.

here my code was like,

List lst = tabledate.getAllData();//return List<Table> Object
Iterator it = lst.iterator();
MyTable mt = new MyTable();//pojo class
while(it.hasNext())
{
     mt=(MyTable)it.next();
     //getting data from getters.
     System.out.println(mt.getxxx());
     System.out.println(mt.getxxx());
     System.out.println(mt.getxxx());
     System.out.println(mt.getxxx());
}


Use a ListIterator to iterate through the list using hasPrevious() and previous():

ListIterator it = lst.listIterator(lst.size());
while(it.hasPrevious()) {
    System.out.println(it.previous());
}


You cannot use an iterator in this case. You will need to use index based access:

int size = lst.size();
for (int i=size - 1; i >= 0; i --)
{
  MyTable mt = (MyTable)lst.get(i);
  ....
}

Btw: there is no need to create a new MyTable() before the loop. This is an instance that will be thrown away immediately and serves no purpose.

0

精彩评论

暂无评论...
验证码 换一张
取 消