PDA

Click to See Complete Forum and Search --> : Java - Collections(Shuffle Elements)


Dillinger4
Sep 29th, 2005, 09:37 AM
The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection.

static void shuffle(List<?> list)
static void shuffle(List<?> list, Random rnd)

The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness.

import java.util.*;

public class ShuffleTest{
public static void main(String[] args){
List<String> sl = new ArrayList<String>();
sl.add("One");
sl.add("Two");
sl.add("Three");
sl.add("Four");
sl.add("Five");
sl.add("Six");
for(String s: sl){
System.out.println(s);
}
System.out.println();
Collections.shuffle(sl);
for(String s: sl){
System.out.println(s);
}
}
}