Skip to content

Shuffle Elements of Java Vector Example

This example shows how to shuffle elements of Vector in Java. This example also shows how to shuffle elements of a vector using the shuffle method of the Collections class.

How to shuffle elements of Vector in Java?

The shuffle method of the Collections class shuffles the elements of the specified List object using the default source of the randomness.

Since the Vector class has implemented the List interface, we can pass an object of the Vector class to this method.

The shuffle method traverses the specified list from the last element to the second element of the list and swaps the current element with the randomly selected element. The elements are randomly selected from the range of the first element of the list to the current element.

Output

The above given shuffle method uses the default randomness source to select random elements from the list. If you want to specify your own source of randomness, you can do so by using the overloaded shuffle method.

This method shuffles the vector elements using the specified random source.

The below given example uses the current time in milliseconds as a seed for the Random number source and then uses that source to shuffle the vector elements.

Output

This example is a part of the Java Vector Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

Leave a Reply

Your email address will not be published.