Java ArrayList reverse example

Java ArrayList reverse example shows how to reverse ArrayList in Java. Example also shows various ways to reverse ArrayList in Java.

How to reverse ArrayList in Java?

There are a couple of ways using which you can reverse ArrayList in Java.

1)    Reverse ArrayList using for loop


2)    Reverse ArrayList using Collections class

The simplest way is to use reverse method of Collections class as given in below example.


Please note that reverse method throws UnsupportedOperationException if the specified List does not support the Set operation.

How does reverse method of Collections class work?

Let’s have a look at source code of Collections class. This snippet is directly taken from the source code of OpenJDK version 6.

As you can see, it uses REVERSE_THRESHOLD and List’s size along with the type of List to determine the best performing approach to reverse the List.  REVERSE_THRESHOLD is defined as,

So if the argument List’s size is less than 18 or if the list is inherited from RandomAccess, it uses for loop to reverse the list by swapping the elements. If the list size is equal to or more than 18, it uses ListIterator to swap the elements and reverse the list.

Note: If you just want to iterate the list in reverse order and do not want to change the original list by reversing it, have a look at how to iterate the ArrayList in reverse order example.

Please let us know your views in the comments section below.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *