Java program to reverse ArrayList

Program

import java.util.ArrayList;
import java.util.Collections;
public class ReverseArrayList {
  public static void main(String[] args) {
    ArrayList arrayList = new ArrayList();
    arrayList.add("Ada");
    arrayList.add("Java");
    arrayList.add("Python");
    arrayList.add("F#");
    arrayList.add("HTML");
    System.out.println("Before Reverse Order: " + arrayList);
    Collections.reverse(arrayList);
    System.out.println("After Reverse Order: " + arrayList);
  }
}

This Java program demonstrates how to reverse the elements of an ArrayList using the Collections.reverse method.

Use Case:

This program is ideal for scenarios where you need to display a list of items in reverse order, such as logs, ranked lists, or timelines.

  1. Importing Required Classes:

    • The program imports java.util.ArrayList and java.util.Collections to use the ArrayList class and the reverse method.
  2. Creating and Populating the ArrayList:

    • An ArrayList named arrayList is created.
    • Elements are added to the ArrayList using the add() method. The elements in this example are names of programming languages.
  3. Displaying the Original List:

    • The System.out.println() method is used to print the ArrayList before reversing.
  4. Reversing the ArrayList:

    • The Collections.reverse() method is called with the ArrayList as its parameter.
    • This method reverses the order of the elements in the ArrayList in place (modifies the original list).
  5. Displaying the Reversed List:

    • After the reverse operation, the ArrayList is printed again to show the elements in reversed order.

Key Features:

  • Usage of Collections.reverse:
    • A simple and efficient way to reverse an ArrayList without manually writing reverse logic.
  • Dynamic ArrayList:
    • The program uses ArrayList, which allows dynamic resizing and operations like reversing.
  • Ease of Use:
    • The Collections.reverse() method makes reversing straightforward and avoids manual coding of reverse logic.
  • Reusability:
    • The method can be applied to any ArrayList, irrespective of the data type.

Output

javac .\ReverseArrayList.java
java ReverseArrayList        
Before Reverse Order: [Ada, Java, Python, F#, HTML]
After Reverse Order: [HTML, F#, Python, Java, Ada]