How to Shuffle Elements of Vector in Java


This case will show us how to shuffle elements of Vector object with shuffle method of Collections class in Java.

Source Code

package com.beginner.examples;

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

public class ShuffleVectorExample {

	
	public static void main(String[] args) {
	
		Vector nums = new Vector();
		
		nums.add(1);
		nums.add(2);
		nums.add(3);
		nums.add(4);
		
		//Use the shuffle() from the Collections utility class to shuffle the CARDS
		Collections.shuffle(nums);
		
		System.out.println("First shuffle:"+nums);
		
		Collections.shuffle(nums);
		
		System.out.println("The second shuffle:"+nums);

	}

}

Output:

First shuffle:[3, 4, 2, 1]
The second shuffle:[4, 1, 3, 2]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments