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.ArrayListandjava.util.Collectionsto use theArrayListclass and thereversemethod.
- The program imports
-
Creating and Populating the ArrayList:
- An
ArrayListnamedarrayListis created. - Elements are added to the
ArrayListusing 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 theArrayListbefore reversing.
- The
-
Reversing the ArrayList:
- The
Collections.reverse()method is called with theArrayListas its parameter. - This method reverses the order of the elements in the
ArrayListin place (modifies the original list).
- The
-
Displaying the Reversed List:
- After the reverse operation, the
ArrayListis 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
ArrayListwithout 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]