In this guide, you will learn about the Collections shuffle() method in Java programming and how to use it with an example.
1. Collections shuffle() Method Overview
Definition:
The shuffle() method of the Collections class in Java is used to randomly permute the elements in a specified list.
Syntax:
Collections.shuffle(List<?> list)
Parameters:
list: The list whose elements are to be shuffled.
Key Points:
- This method uses a default source of randomness which is suitable for informal purposes.
- It throws UnsupportedOperationException if the specified list or its list-iterator doesn't support the set operation.
- For more controlled randomness, there is an overloaded shuffle() method that allows the user to specify a Random object.
2. Collections shuffle() Method Example
import java.util.*;
public class CollectionsShuffleExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
// Shuffling the list
Collections.shuffle(numbers);
System.out.println("Shuffled list: " + numbers);
}
}
Output:
Shuffled list: [3, 1, 5, 2, 4] // Note: The output will vary as the list is shuffled randomly.
Explanation:
In the provided example, we create a list of integers from 1 to 5. We then use the shuffle() method to randomly rearrange the order of its elements and print the shuffled list.
Comments
Post a Comment
Leave Comment