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.
1 |
public static void shuffle(List<?> list) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Collections; import java.util.Vector; public class VectorShuffleElements { public static void main(String[] args) { Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); /* * To shuffle the vector elements, use * the shuffle method of the Collections class */ Collections.shuffle(vNumbers); System.out.println("Vector contains: " + vNumbers); } } |
Output
1 |
Vector contains: [20, 40, 50, 30, 10] |
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.
1 |
public static void shuffle(List<?> list, Random random) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); //create new Random with current time as seed long seed = System.currentTimeMillis(); Random random = new Random(seed); //shuffle the vector using the created random Collections.shuffle(vNumbers, random); System.out.println("Vector contains: " + vNumbers); |
Output
1 |
Vector contains: [40, 20, 50, 30, 10] |
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