List Manipulation: Reverse a List

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:

  1. Import Statements: We import the necessary classes, including ArrayList and List from the java.util package.
  2. Creating the Original List: We create an ArrayList named originalList and populate it with some integers (1, 2, 3, 4, 5 in this case).
  3. Printing the Original List: We print the contents of the originalList using System.out.println().
  4. Reversing the List: We call the reverseList() method to reverse the originalList. The reverseList() method takes a generic List as input and returns a new reversed List.
  5. reverseList() Method: This method uses a for loop to iterate through the elements of the input list in reverse order. It creates a new ArrayList named reversed to store the reversed elements.
  6. 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 the reversed list using the add() method.
  7. 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.
  8. 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.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *