Java Shuffle Array shuffle()

Java Shuffle Array shuffle()


Java collections framework comes with two classes Collections and Arrays (from java.util) to operate on the elements of collection classes (data structures) and arrays. To shuffle the elements of a data structure, the Collections class includes a method shuffle() but Arrays class does not come with one.

To shuffle the elements of an array, we must write our own algorithm or other way is convert the array elements into a collections class and then apply shuffle() method. Following programs uses both with different styles.

Following is the method signature of shuffle() method as defined in Collections class (not Array class).

  • static void shuffle(List list1): Shuffles the existing elements of list1 randomly. For repeated execution of the method, elements with different order are obtained.

Following program shuffles the elements, but here we write the code ourselves like in C/C++.

Java Shuffle Array shuffle()

java.util. package comes with class Random used to generate random integers, doubles etc. with seed or without seed.

The nextInt() method generates a random integer number. But passing marks.length as parameter generates random integers from 0 to marks.length.

A marks integer array is created and assigned with 0 to 9 values in a for loop.

To print the elements of an array it takes a for loop. But there is shortcut in Java. Arrays.toString(marks) prints straightaway the marks elements.

Using the nextInt() method of Random class, each element of the array is assigned with random integer value. Executing the same for loop multiple times, different shuffling will be done. Observe the screen shot.

Let us go for Java Shuffle Array shuffle() and see how much code comes down and also simple.

Java Shuffle Array shuffle()

A string array numbers is initialized and printed the values with toString() method of Arrays class.

Now let us convert the array elements into a List. The asList() method of Array class returns a List object, here it is myList, containing the same elements of array numbers.

Now apply the shuffle() method of Collections class on myList. Now the List elements are shuffled.

If required, you can get back the array from myList, as in the above code, with toArray() method..

Now you have seen how to convert array elements into List (with asList()) and List to array (with toArray()). It is how the Java designers made both arrays and collections classes interoperable. Separate programs are available to covert array to ArrayList and ArrayList to array.

Leave a Reply

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