Collection public static void shuffle(List list, Random rnd) Method Example Program

Randomly permute the specified list using the specified source of randomness.


package com.candidjava;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

 * @author karthikeyan.T
 * @description the following code shows how to use Collections.shuffle(List <?>
 *              list, Random rnd) method.
public class CollectionsShuffleRandom {

	public static void main(String args[]) {
		List<Integer> list = new LinkedList<Integer>();
		System.out.println("List before shuffle: " + list);
		Collections.shuffle(list, new Random());
		System.out.println("List after shuffle: " + list);


List before shuffle: [53, 12, 45, -33]
List after shuffle: [12, -33, 45, 53]


public static void shuffle(List<?> list, Random rnd)
Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.
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.

list - the list to be shuffled.
rnd - the source of randomness to use to shuffle the list.
UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.

Related Post