Thursday, July 20, 2023

How to reverse ArrayList in Java with Example

You can reverse ArrayList in Java by using the reverse() method of java.util.Collections class. This is one of the many utility methods provided by the Collections class e.g. sort() method for sorting ArrayList. The Collections.reverse() method also accepts a List, so you not only can reverse ArrayList but also any other implementation of List interface e.g. LinkedList or Vector or even a custom implementation. This method has a time complexity of O(n) i.e. it runs on linear time because it uses ListIterator of the given list.  It reverses the order of an element in the specified list. 

By the way, you cannot reverse an ArrayList using this method if the specified ArrayList or it's ListIterator doesn't support set() operation. It switches between two algorithms depending upon the size of List or if List implements RandomAccess interface like ArrayList.

If a number of elements in List are less than REVERSE_THRESHOLD, which is equal to 18 then it uses for loop for swapping elements otherwise it uses list iterator. If you want to learn more about how the reverse() method of Collections works, you can see it's code from JDK itself or in the next section.

By the way, this is a typesafe generic method and you can use it to reverse Integer, String, Float or any kind of List in Java. You can also see the classic book Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn more about key classes of the Java Development Kit.




Java Program to Reverse an ArrayList in Java

Here is my code example of reversing an ArrayList of Integer.  You can see that we have added numbers on increasing order but after calling reverse() method, it prints them on decreasing order. Unlike popular misconception, Comparable or Comparator is not used while reversing ArrayList in Java. Though they are used if you want to sort Array in Java.

import java.util.ArrayList;
import java.util.Collections;

/**
 * Java program to reverse ArrayList by using Collections.reverse()
 * method. This method will work for any kind of ArrayList e.g.
 * integer list or String list, but this method will not work
 * for an ArrayList which doesn't support set() operation. 
 * 
 * @author WINDOWS 8
 */

public class ArrayListReverseDemo {

    public static void main(String args[]) {

        ArrayList<String> listOfInts = new ArrayList<>();
        listOfInts.add("1");
        listOfInts.add("2");
        listOfInts.add("3");
        listOfInts.add("4");
        listOfInts.add("5");
        
        System.out.println("Before Reversing : " + listOfInts);
        Collections.reverse(listOfInts);
        System.out.println("After Reversing : " + listOfInts);
       

    }

}

Output
Before Reversing : [1, 2, 3, 4, 5]
After Reversing : [5, 4, 3, 2, 1]


How Collections.reverse() method works in Java

Here is the code snippet from java.util.Collections class which you can use to reverse an ArrayList or any kind of List in Java. You can see that it uses set() method of List interface for swapping elements and that's why you cannot reverse a read-only ArrayList because it doesn't support set() operation.


ArrayList reverse Example in Java






Logic of Collections.reverse() method

Here is the logic and explanation of how the Collections.reverse() method works and how it reverse the given collection. 
/**
     * Reverses the order of the elements in the specified list.<p>
     *
     * This method runs in linear time.
     *
     * @param  list the list whose elements are to be reversed.
     * @throws UnsupportedOperationException if the specified list or
     *         its list-iterator does not support the <tt>set</tt> operation.
     */
    public static void reverse(List<?> list) {
        int size = list.size();
        if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
            for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
                swap(list, i, j);
        } else {
            ListIterator fwd = list.listIterator();
            ListIterator rev = list.listIterator(size);
            for (int i=0, mid=list.size()>>1; i<mid; i++) {
                Object tmp = fwd.next();
                fwd.set(rev.previous());
                rev.set(tmp);
            }
        }
    }


That's all about how to reverse ArrayList in Java. Though you can always write your method to reverse an ArrayList, it won't be much different than how you reverse an Array in Java, it's always better to use a function from the JDK library. Why? because they are well tested for programming bugs and corner cases and they are much more optimized than you think, because of wider audiences who have used and improved them already. Let us know if you know a faster way to reverse ArrayList in Java.  

2 comments:

  1. How do you reverse an array in Java? Can you give example of reversing an int and String array please

    ReplyDelete
  2. if it is an array of integers, then you can convert it to an integer and then reverse it. or else you can swap the end elements with the help of a for loop ranging from 0 to Length/2. you can do the same with the staring array too. Arrays.toString() will give you a single string from a array of strings, and dn just reverse it.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.