Problem Statement: Implement a Java program to reverse a List without using the built-in Collections.reverse() method.
Here’s a Java program that reverses a list without using the built-in Collections.reverse()
method. I’ll provide a step-by-step explanation of the logic used in the program.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.List;
public class ReverseListExample {
public static void main(String[] args) {
List<Integer> originalList = new ArrayList<>();
originalList.add(1);
originalList.add(2);
originalList.add(3);
originalList.add(4);
originalList.add(5);
System.out.println("Original List: " + originalList);
List<Integer> reversedList = reverseList(originalList);
System.out.println("Reversed List: " + reversedList);
}
// Method to reverse a list
public static <T> List<T> reverseList(List<T> inputList) {
List<T> reversed = new ArrayList<>();
for (int i = inputList.size() - 1; i >= 0; i--) {
reversed.add(inputList.get(i));
}
return reversed;
}
}
OUTPUT:
Original List: [1, 2, 3, 4, 5]
Reversed List: [5, 4, 3, 2, 1]
Explanation:
- Import Statements: We import the necessary classes, including
ArrayList
andList
from thejava.util
package. - Creating the Original List: We create an
ArrayList
namedoriginalList
and populate it with some integers (1, 2, 3, 4, 5 in this case). - Printing the Original List: We print the contents of the
originalList
usingSystem.out.println()
. - Reversing the List: We call the
reverseList()
method to reverse theoriginalList
. ThereverseList()
method takes a genericList
as input and returns a new reversedList
. reverseList()
Method: This method uses afor
loop to iterate through the elements of the input list in reverse order. It creates a newArrayList
namedreversed
to store the reversed elements.- Adding Elements in Reverse Order: Within the loop, we use the
inputList.get(i)
method to retrieve elements from the input list in reverse order, and then add them to thereversed
list using theadd()
method. - Returning the Reversed List: After the loop, the
reversed
list contains the elements of the input list in reverse order. The method returns this reversed list. - Printing the Reversed List: We print the contents of the reversed list using
System.out.println()
.
By following these steps, the program demonstrates how to reverse a list without using the built-in Collections.reverse()
method. The reverseList()
method implements the logic to reverse the list by iterating through it in reverse order and adding the elements to a new list.
See also: ArrayList Manipulation: add, remove Elements, find size.