![]() |
VOOZH | about |
The Collections.reverse() method in Java is used to reverse the order of elements in a List. It is part of the java.util.Collections class and modifies the original list directly.
Example: Reversing an ArrayList
Original List : [practice, code, quiz, geeksforgeeks] Modified List: [geeksforgeeks, quiz, code, practice]
Collections.reverse(List<?> list)
List as input. Example: Reversing a LinkedList
Original List : [practice, code, quiz, geeksforgeeks] Modified List: [geeksforgeeks, quiz, code, practice]
If we peek through the above programs then there is only a minute signature detail that we are just creating an object of LinkedList class instead of Array class as seen in example1A. For LinkedList, we just did change as shown below in the above codes:
In the LinkedList example, we simply replace ArrayList with LinkedList while keeping the List interface reference the same.
Example: Reversing an array: Arrays class in Java doesn't have a reverse method. We can use Collections.reverse() to reverse an array also as shown below as follows:
Original Array : [10, 20, 30, 40, 50] Modified Array : [50, 40, 30, 20, 10]