In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse()
method. This method requires an argument with List
type. Because of this we need to convert the array to a List
type first. We can use the Arrays.asList()
to do the conversion. And then we reverse it. To convert the List
back to array we can use the Collection.toArray()
method.
Let’s see the code snippet below:
package org.kodejava.util;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayReverse {
public static void main(String[] args) {
// Creates an array of Integers and print it out.
Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
System.out.println("Arrays.toString(numbers) = " +
Arrays.toString(numbers));
// Convert the int arrays into a List.
List<Integer> numberList = Arrays.asList(numbers);
// Reverse the order of the List.
Collections.reverse(numberList);
// Convert the List back to array of Integers
// and print it out.
numberList.toArray(numbers);
System.out.println("Arrays.toString(numbers) = " +
Arrays.toString(numbers));
}
}
The output of the code snippet above is:
Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]