Skip to content

Java ArrayList reverse example

Java ArrayList reverse example shows how to reverse ArrayList in Java. The example also shows various ways to do that in detail.

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

Output

2) Reverse ArrayList using Collections class

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

Output

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

How does the reverse method of the Collections class work?

Let’s have a look at the source code of the 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.

This example is a part of the ArrayList in Java tutorial.

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

About the author

Leave a Reply

Your email address will not be published.