Java program to reverse array using Collections

Program

import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class ReverseArrayUsingCollections {
  public static void main(String[] args) {    
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    Integer inputArray[] = new Integer[size];
    System.out.println("Enter the elements of the array: ");
    for (int i = 0; i < size; i++) {
      inputArray[i] = reader.nextInt();
    }
    System.out.println("Array in reverse order: ");
    Collections.reverse(Arrays.asList(inputArray)); 
    System.out.println(Arrays.asList(inputArray)); 
  }
}

This Java program demonstrates how to reverse an array using the Collections.reverse() method by converting the array into a List.

  1. Importing Required Classes:

    • The program imports java.util.Scanner for user input, java.util.Arrays for array manipulation, and java.util.Collections for reversing the list.
  2. Reading Array Size:

    • The user is prompted to enter the size of the array.
    • A Scanner object is used to read the input and store the size.
  3. Creating and Populating the Array:

    • An array of type Integer[] is created with the specified size.
    • The user is prompted to enter the elements of the array one by one, which are stored in the array.
  4. Reversing the Array:

    • The array is converted to a List using Arrays.asList(inputArray). This allows the use of methods from the Collections class.
    • The Collections.reverse() method reverses the order of elements in the list in place.
  5. Displaying the Reversed Array:

    • The reversed list is displayed using System.out.println(Arrays.asList(inputArray)).

Key Features:

  • Conversion to List:
    • Arrays in Java do not have methods for directly manipulating elements like reversing. Converting the array to a List allows the use of the Collections utility methods.
  • Reversing with Collections.reverse():
    • The reverse method modifies the list in place, reversing the order of the elements.

Advantages:

  1. Ease of Use:
    • Leveraging the Collections.reverse() method simplifies reversing logic.
  2. Reusability:
    • The method can be applied to any List created from arrays, regardless of the size or data type.
  3. Use of Integer[]:
    • The array is defined as Integer[] because Arrays.asList() requires objects, and primitive arrays like int[] cannot be directly converted.
  4. Performance:
    • This method is efficient for small to moderate-sized arrays. For very large arrays, custom implementations could be more memory-efficient.

Output

javac .\ReverseArrayUsingCollections.java
java ReverseArrayUsingCollections        
Enter the required size of the array: 
5
Enter the elements of the array: 
100
200
300
400
500
Array in reverse order: 
[500, 400, 300, 200, 100]