Java's Collections.reverse()
method is a convenient tool for reversing the order of elements in a list. This method is a part of the java.util.Collections
class, which provides several useful methods for working with collections.
The Collections.reverse()
method is primarily used to reverse the order of elements in a list. This method can be used with both ArrayList and LinkedList, which are two of the most commonly used list implementations in Java.
Here is an example code that demonstrates the use of the Collections.reverse()
method to reverse an ArrayList:
javaimport java.util.*;
public class ReverseArrayListExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
System.out.println("Original List: " + list);
Collections.reverse(list);
System.out.println("Reversed List: " + list);
}
}
Output:
javaOriginal List: [10, 20, 30]
Reversed List: [30, 20, 10]
The output of this code demonstrates that the Collections.reverse()
method has reversed the order of the elements in the original list.
Note that the Collections.reverse()
method can also be used with LinkedLists by simply replacing ArrayList
with LinkedList
in the list declaration.
Here is an example code that demonstrates the use of the Collections.reverse()
method to reverse an array:
javaimport java.util.*;
public class ReverseArrayExample {
public static void main(String[] args) {
Integer[] arr = {10, 20, 30};
List<Integer> list = Arrays.asList(arr);
System.out.println("Original Array: " + Arrays.toString(arr));
Collections.reverse(list);
System.out.println("Reversed Array: " + Arrays.toString(arr));
}
}
Output:
javaOriginal Array: [10, 20, 30]
Reversed Array: [30, 20, 10]
This code converts the array to a list using the Arrays.asList()
method and then passes the list to the Collections.reverse()
method to reverse the order of the elements in the array. Note that the Collections.reverse()
method does not modify the original array, but instead modifies the list that is created from the array.
In summary, the Collections.reverse()
method is a useful tool for reversing the order of elements in a list or array in Java. It is a part of the java.util.Collections
class and can be used with both ArrayLists and LinkedLists. Additionally, the Arrays.asList()
method can be used to convert an array to a list to use the Collections.reverse()
method.