Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can a Collection be traversed in reverse order?

 
Jessica James
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..

I am using a List of Objects to display..
When I click a Link, it has to be displayed in the reverse order..
Is there any way to do this..

Please help me..

Thanks in advance..
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can reverse a List with Collections.reverse(). However, that really does reverse it permanently.

You can use a "for" loop and get(int) to go backwards through the list. This is efficient if the implementation is something like an ArrayList, but inefficient if it's something like a LinkedList.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is also a way to do this more efficiently using a ListIterator, without reversing the original list.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cool. Never had to do that, but shall now endeavour to remember it, in case it comes up.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic