Monday 25 May 2015

How to shuffle elements in Vector


import java.util.Collections;
import java.util.Vector;

public class Shuffle {

    public static void main(String[] args) {
      
        Vector<String> vector = new Vector<String>();
        //add element in vector
        vector.add("cricket");
        vector.add("hockey");
        vector.add("football");
        vector.add("tennish");
      
        // print vector
        System.out.println("Vector = "+vector);
               
        /*
         * Randomly permutes the specified list using a
         *  default source of randomness.
         */
        Collections.shuffle(vector);
      
        System.out.println("Vector after first Shuffle = "+vector);
      
        Collections.shuffle(vector);
      
        System.out.println("Vector after second Shuffle = "+vector);
      
    }
}
   
Output:
Vector = [cricket, hockey, football, tennish]

Vector after first Shuffle = [tennish, cricket, football, hockey]

Vector after second Shuffle = [cricket, hockey, tennish, football]

No comments:

Post a Comment