# Collection public static void shuffle(List list) Method Example Program

Randomly permutes the specified list using a default source of randomness.

#### Program

```package com.candidjava;

import java.util.*;

/**
*
* @author karthikeyan.T
* @description The following example shows the usage of Collections.shuffle()
*/
public class CollectionsShuffle {

public static void main(String args[]) {
List arrlist = new ArrayList();
System.out.println("Initial collection: " + arrlist);
Collections.shuffle(arrlist);
System.out.println("Final collection after shuffle: " + arrlist);
}
}
```

#### Output

Initial collection: [Karthik, Mohan, Kamal, Hari, Anand, Vinod]
Final collection after shuffle: [Vinod, Mohan, Karthik, Anand, Hari, Kamal]

#### Explanation

public static void shuffle(List<?> list)
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
The hedge "approximately" is used in the foregoing description because default source of randomness is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.

This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place.

Parameters:
list - the list to be shuffled.
Throws:
UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.

Related Post