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.
-
Importing Required Classes:
- The program imports
java.util.ArrayList
andjava.util.Collections
to use theArrayList
class and thereverse
method.
- The program imports
-
Creating and Populating the ArrayList:
- An
ArrayList
namedarrayList
is created. - Elements are added to the
ArrayList
using theadd()
method. The elements in this example are names of programming languages.
- An
-
Displaying the Original List:
- The
System.out.println()
method is used to print theArrayList
before reversing.
- The
-
Reversing the ArrayList:
- The
Collections.reverse()
method is called with theArrayList
as its parameter. - This method reverses the order of the elements in the
ArrayList
in place (modifies the original list).
- The
-
Displaying the Reversed List:
- After the reverse operation, the
ArrayList
is printed again to show the elements in reversed order.
- After the reverse operation, the
Key Features:
- Usage of
Collections.reverse
:- A simple and efficient way to reverse an
ArrayList
without manually writing reverse logic.
- A simple and efficient way to reverse an
- Dynamic ArrayList:
- The program uses
ArrayList
, which allows dynamic resizing and operations like reversing.
- The program uses
- Ease of Use:
- The
Collections.reverse()
method makes reversing straightforward and avoids manual coding of reverse logic.
- The
- Reusability:
- The method can be applied to any
ArrayList
, irrespective of the data type.
- The method can be applied to any
Output
javac .\ReverseArrayList.java
java ReverseArrayList
Before Reverse Order: [Ada, Java, Python, F#, HTML]
After Reverse Order: [HTML, F#, Python, Java, Ada]