In this guide, you will learn about the Collections reverse() method in Java programming and how to use it with an example.
1. Collections reverse() Method Overview
Definition:
The reverse() method of the Collections class in Java is used to reverse the order of elements in a specified list.
Syntax:
Collections.reverse(List<?> list)
Parameters:
list: The list whose elements are to be reversed.
Key Points:
- After executing the method, the list provided will be modified such that the order of its elements is reversed.
- It throws UnsupportedOperationException if the specified list or its list-iterator doesn't support the set operation.
- This is a very efficient method to reverse a list as it doesn't involve any copying of elements.
2. Collections reverse() Method Example
import java.util.*;
public class CollectionsReverseExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
// Reversing the list
Collections.reverse(numbers);
System.out.println("Reversed list: " + numbers);
}
}
Output:
Reversed list: [5, 4, 3, 2, 1]
Explanation:
In the provided example, we create a list of integers from 1 to 5. We then use the reverse() method to reverse the order of its elements and print the reversed list.
Comments
Post a Comment
Leave Comment