Reverse An Array In Java Inbuilt Function
Reversing an array is a common operation in programming that involves rearranging its elements in the opposite order. In Java, you can achieve this efficiently using built-in utility functions provided by the language's standard library. In this article, you will learn how to reverse an array in Java using an inbuilt function, making your code concise and robust.
Problem Statement
Often, developers need to process data stored in arrays from the last element to the first, or simply present data in reverse order. For instance, displaying a list of recent transactions from newest to oldest, or processing a stack-like data structure where the last item added is the first one processed. Manually implementing a reversal loop can be error-prone and less readable compared to using an optimized library function.
Example
Consider an array of integers: [10, 20, 30, 40, 50].
After reversing, the array should become: [50, 40, 30, 20, 10].
Background & Knowledge Prerequisites
To understand array reversal in Java using inbuilt functions, you should be familiar with:
- Java Arrays: Basic understanding of how arrays work, declaration, and initialization.
- Java Collections Framework: An overview of interfaces like
Listand concrete classes likeArrayList. - Wrapper Classes: Knowledge of how primitive types (like
int) correspond to their wrapper classes (likeInteger). -
ArraysUtility Class: Familiarity with static methods provided byjava.util.Arrays. -
CollectionsUtility Class: Understanding of static methods provided byjava.util.Collections.
Use Cases or Case Studies
Reversing arrays is useful in various scenarios:
- Displaying Data: Showing search results, log entries, or transaction history in reverse chronological order.
- Algorithm Implementations: Certain algorithms, like some string manipulation tasks or data structure operations (e.g., reversing a linked list), might require array reversal as a sub-step.
- Stack Simulation: When an array is used to simulate a stack, and you need to iterate through elements from top to bottom without actually popping them.
- Palindromes: Checking if a sequence (like a string or a number represented as an array of digits) is a palindrome often involves comparing it to its reverse.
- Game Development: Reversing sequences of moves or animations.
Solution Approaches
Java's Collections utility class provides a powerful reverse() method that can reverse the order of elements in a List. While it doesn't directly operate on primitive arrays (int[], char[]), it can be effectively used with object arrays (Integer[], String[]) by converting them to a List first.
Approach 1: Using Collections.reverse()
This approach leverages the Collections.reverse() method after converting the array into a List. It's concise and readable for object arrays.
One-line summary: Convert the array to a List using Arrays.asList(), then use Collections.reverse() to reverse the order of elements in the list.
Code example:
// Reverse Array using Collections.reverse()
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare and initialize an array of Integer objects
// Note: Collections.reverse() works on List, and Arrays.asList() for primitives
// creates a List<int[]> not List<Integer>. So, we use Integer[] here.
Integer[] originalArray = {10, 20, 30, 40, 50};
System.out.println("Original Array: " + Arrays.toString(originalArray));
// Step 2: Convert the array to a List
List<Integer> list = Arrays.asList(originalArray);
// Step 3: Reverse the list using Collections.reverse()
// This modifies the underlying array linked by Arrays.asList()
Collections.reverse(list);
// Step 4: Print the reversed array
System.out.println("Reversed Array: " + Arrays.toString(originalArray));
// --- Handling Primitive int[] arrays ---
System.out.println("\\n--- Handling Primitive int[] arrays ---");
int[] primitiveArray = {1, 2, 3, 4, 5};
System.out.println("Original Primitive Array: " + Arrays.toString(primitiveArray));
// To reverse a primitive array using Collections.reverse(),
// it must first be converted to an object array (Integer[]) or a List<Integer>.
// One way is to manually box elements into a new Integer[] array.
Integer[] boxedArray = new Integer[primitiveArray.length];
for (int i = 0; i < primitiveArray.length; i++) {
boxedArray[i] = primitiveArray[i];
}
List<Integer> primitiveList = Arrays.asList(boxedArray);
Collections.reverse(primitiveList);
// Copy elements back to the primitive array if needed
for (int i = 0; i < primitiveArray.length; i++) {
primitiveArray[i] = boxedArray[i];
}
System.out.println("Reversed Primitive Array: " + Arrays.toString(primitiveArray));
}
}
Sample output:
Original Array: [10, 20, 30, 40, 50]
Reversed Array: [50, 40, 30, 20, 10]
--- Handling Primitive int[] arrays ---
Original Primitive Array: [1, 2, 3, 4, 5]
Reversed Primitive Array: [5, 4, 3, 2, 1]
Stepwise explanation:
- Declare
Integer[]: An array ofIntegerobjects (originalArray) is created. This is crucial becauseArrays.asList()creates aListof the actual array's type. Forint[], it would create aList(a list containing oneint[]object), notList. Arrays.asList(originalArray): This static method from thejava.util.Arraysclass converts theoriginalArrayinto aList. Importantly, thisListis a fixed-size view of the original array; changes to theListare reflected in the array, and vice versa. It does not create a newArrayList.Collections.reverse(list): The staticreverse()method fromjava.util.Collectionsis called with thelist. This method directly modifies the order of elements within thelist, which, because of the view provided byArrays.asList(), also reverses the elements inoriginalArray.- Print Result: The
Arrays.toString()method is used again to print theoriginalArray, showing its elements in reversed order. - Handling Primitive Arrays: For primitive arrays like
int[],Arrays.asList()does not produce aList. Instead, it wraps the entireint[]into a single-elementList. To useCollections.reverse()with primitive arrays, you first need to convert them into their corresponding wrapper object array (Integer[]) or aList. The example demonstrates creating a newInteger[]array, boxing the primitive values into it, then applying theCollections.reverse()method. Finally, the reversed elements are copied back to the original primitive array.
Conclusion
Reversing an array in Java, particularly an array of objects, is straightforward and efficient using the Collections.reverse() method in conjunction with Arrays.asList(). While primitive arrays require an extra step of boxing their elements into wrapper objects, this approach maintains readability and leverages highly optimized library functions. Using these built-in utilities enhances code quality and reduces the likelihood of bugs compared to manual loop-based reversal.
Summary
-
Collections.reverse()is the primary inbuilt method for reversing elements in aList. -
Arrays.asList()converts an object array (e.g.,Integer[],String[]) into a fixed-sizeListview, allowingCollections.reverse()to modify the original array. - For primitive arrays (
int[],char[]), direct use ofArrays.asList()withCollections.reverse()is not viable for element reversal. - Primitive arrays require boxing their elements into wrapper objects (e.g.,
Integer[]) or creating aListof wrapper objects to useCollections.reverse(). - This approach is concise, readable, and less error-prone than manual implementations.