aspose file tools*
The moose likes Java in General and the fly likes Using enhanced for loop to iterate in reverse order ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using enhanced for loop to iterate in reverse order ?" Watch "Using enhanced for loop to iterate in reverse order ?" New topic
Author

Using enhanced for loop to iterate in reverse order ?

Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 844
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?


SCJP 1.4, SCWCD 5, SCBCD 5, OCPJWSD 5,SCEA-1, Started Assignment Part 2
My blog- http://rkydesigns.blogspot.com
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36579
    
  16
As far as I know, not at all. The for-each loop only goes in one direction.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
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

Joined: Mar 05, 2008
Posts: 2970
    
    9
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

Joined: Jul 17, 2008
Posts: 844
thank you Mike,

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

Snapshot of the code:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using enhanced for loop to iterate in reverse order ?
 
Similar Threads
Enhanced Loop
new to working with arrays
Enhanced For Loop Problem
queries
Sort the Array in reverse order