• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using enhanced for loop to iterate in reverse order ?

 
Amandeep Singh
Ranch Hand
Posts: 850
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using the standard for loop, i can loop in reverse order from largest to smallest. but how this can accomplished using the enhanced for loop?
 
Campbell Ritchie
Sheriff
Posts: 48374
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, not at all. The for-each loop only goes in one direction.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amandeep:

You'd have to go through the steps of creating another List/Array, copying the elements in reverse order to the new List/Array, then using the for each loop on that. It should be relatively easy to do.

John.
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could use Collections.reverse() to reverse the order of the existing list.

But offhand, it's probably easier to just use the old-fashioned for loop. Enhanced for isn't designed to handle everything - it just handles the most common case, and handles it very well.

If there's any chance that you List might be a LinkedList rather than an ArrayList, you should probably avoid using get(), and instead use the ListIterator:

This is because get() can be extremely inefficient for a long LinkedList, while iterator operations like next() and previous() are still very efficient.
 
Amandeep Singh
Ranch Hand
Posts: 850
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you Mike,

i am going to use the Collections.reverse(List)

Snapshot of the code:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic