Can one do a for each loop in java in reverse order?
Here's how you can reverse a for-each
loop using a ListIterator
:
Output: c b a
We utilize ListIterator
's hasPrevious()
and previous()
methods for reverse iteration.
Crafting a custom solution
Building a Reversible Iterable
If reverse traversals are common in your project, a reusable class may save the day! Here's a decorator providing reverse iteration over a List
without modifying it:
Rows of code were flipped just so you can flip through a List
backwards.
Voice of practicality: Google Guava
If you trust a library to own your jarfile, Google Guava has got you covered:
This is an efficient maneuver, but weigh the costs before you add an external library.
Minding Efficiency with ArrayList
ArrayList has random access, meaning it proudly provides constant-time iterations over elements. A simple for loop can sometimes be more efficient:
When using Collections.reverse()
, remember to call it outside the loop:
Careful, though, this method changes your list's original selection.
Handling divider situations
Cloning safely
For reversing a list via cloning, remember: clone()
makes a shallow copy. When handling mutable objects, go for a deep copy to avoid unintended ripple effects:
Synchronizing for safety
If the list is modified during iteration, wrap the iteration inside a synchronized block or use concurrent collections to prevent the dreaded race:
Removing elements while reversing
With a ListIterator
, you can remove items while iterating in reverse, unlike a for-each loop:
But watch out for your steps, you don't want to trip over an unexpected ConcurrentModificationException
.
Was this article helpful?