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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *