1. Introduction
Reversing the order of elements in an ArrayList is a common operation in Java. Java provides a utility class Collections, which has a reverse method to reverse the order of elements in a List. In this post, we will demonstrate how to reverse the order of elements in an ArrayList using the Collections.reverse() method.
2. Program Steps
1. Create an ArrayList and add some elements to it.
2. Print the original ArrayList.
3. Use the Collections.reverse() method to reverse the order of the elements in the ArrayList.
4. Print the ArrayList again to show that the order of the elements has been reversed.
3. Code Program
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListReverse {
public static void main(String[] args) {
// Step 1: Create an ArrayList and add some elements to it
ArrayList<String> animals = new ArrayList<>();
animals.add("Cat");
animals.add("Dog");
animals.add("Elephant");
// Step 2: Print the original ArrayList
System.out.println("Original ArrayList: " + animals);
// Step 3: Use Collections.reverse() method to reverse the order of the elements in the ArrayList
Collections.reverse(animals);
// Step 4: Print the ArrayList again to show that the order of the elements has been reversed
System.out.println("ArrayList in Reverse Order: " + animals);
}
}
Output:
Original ArrayList: [Cat, Dog, Elephant] ArrayList in Reverse Order: [Elephant, Dog, Cat]
4. Step By Step Explanation
Step 1: We create an ArrayList named animals and add the elements "Cat", "Dog", and "Elephant" to it.
Step 2: We print the original ArrayList to the console.
Step 3: We call the Collections.reverse() method and pass the ArrayList as a parameter to reverse the order of its elements. The Collections.reverse() method takes a List and reverses the order of the elements in the given List.
Step 4: We print the ArrayList again to show that the order of the elements has been reversed.