![]() |
VOOZH | about |
shuffle() method of Collections class as the class name suggests is present in utility package known as java.util that shuffles the elements in the list.
There are two ways with which we can use to implement in our programs that are as follows:
Way 1: Shuffling a given list using the pre-defined source of randomness.
Syntax:
public static void shuffle(List mylist)
Exception Thrown: UnsupportedOperationException is thrown if the given list or its list-iterator does not support the set operation.
Example:
Original List : [code 1="quiz," 2="geeksforgeeks," 3="quiz," 4="practice," 5="qa" language=","][/code] Shuffled List : [quiz, quiz, geeksforgeeks, code, practice, qa]
Way 2: Shuffling a given list using the user-provided source of randomness.
Here an additional parameter that is provided which above specified "rndm" is the source of randomness to shuffle the list.
Syntax:
public static void shuffle(List mylist, Random rndm)
Parameters: Here it takes two parameters as listed
Exceptions: UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.
Example:
Original List : [code 1="quiz," 2="geeksforgeeks," 3="quiz," 4="practice," 5="qa" language=","][/code] Shuffled List with Random() : [geeksforgeeks, qa, quiz, code, quiz, practice] Shuffled List with Random(3) : [practice, code, qa, quiz, geeksforgeeks, quiz] Shuffled List with Random(5) : [code 1="quiz," 2="geeksforgeeks," 3="practice," 4="qa," 5="quiz" language=","][/code]
But do remember certain important points as listed below prior to implementing this method as listed below as follows:
Note: If the provided list does not implement the RandomAccess interface, like LinkedList, and is large, it first copies the list into an array, then shuffles the array copy, and finally copies the array back into the list. This makes sure that the time remains linear.