Let say we have a Collection of elements which we want to do some operations,
for example shuffling the elements in a Vector.
In this cases, the shuffle static method will be very usefull in helping out to do the job.
We don’t even need to think of complicated algorithms to shuffle the Vector elements.
The shuffle method is a static method in class Collections.
It has two overloaded methods:
* shuffle(List list) - Randomly permutes the specified list using a default source of randomness.
* shuffle(Listlist, Random rnd) - Randomly permute the specified list using the specified source of randomness.
Since List is an Interface, therefore all it’s sub-class cen be used to pass as parameters.
In the example below, i used Vector objects and shuffled the Vector elements.
import java.util.Vector;
import java.util.Collections;
public class ShuffleList
{
public static void main (String... args)
{
String val[] = {"1","2","3","4","5","6","7","8","9","10"};
Vector<String> vecStr = new Vector<String>();
/*Loop the array and add all the array elements into Vector object*/
for(String str : val)
vecStr.add(str);
/*Print out the Vector elements*/
System.out.println("Elements in Vector before shuffle: ");
for(String v : vecStr)
System.out.print(v+" ");
/*Shuffle the Vector elements with Colections class*/
Collections.shuffle(vecStr);
/*Print out the Vector elements*/
System.out.println("\n\nElements in Vector after shuffle: ");
for(String v : vecStr)
System.out.print(v+" ");
System.out.print("\n");
}
}
And here’s the output of execution of above code:
Elements in Vector before shuffle:
1 2 3 4 5 6 7 8 9 10
Elements in Vector after shuffle:
7 10 8 4 5 2 9 6 1 3
Press any key to continue . . .