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++.

import java.util.*;           // for Arrays and Random
public class Demo
{
  public static void main(String args[])
  {
    Random rand = new Random();
    int marks[] = new int[10];
    for(int i = 0; i < 10; i++)
    {
      marks[i] = i;
    }
    System.out.println("Original array: " + Arrays.toString(marks));
   
	        // to shuffle the elements the C style
    for(int i = 0; i < 10; i++)
    {
      int someInt = rand.nextInt(marks.length);
      marks[i] = someInt;
    }
    System.out.println("Shuffled array: " + Arrays.toString(marks));
   }
}

Java Shuffle Array shuffle()

     Random rand = new Random();

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

     int someInt = rand.nextInt(marks.length);

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

     int marks[] = new int[10];

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

     System.out.println("Original array: " + Arrays.toString(marks));

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.

     for(int i = 0; i < 10; i++)
     {
       int someInt = rand.nextInt(marks.length);
       marks[i] = someInt;
     }

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.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo
{
  public static void main(String args[])
  {
    String numbers[] = { "one", "two",  "three", "four", "five", "six" };
    System.out.println("Original array: " + Arrays.toString(numbers));
   
    		                                 // CONVERTING ARRAY TO LIST
    List myList = Arrays.asList(numbers);
    System.out.println("\nOriginal list: " + myList);  

    Collections.shuffle(myList);
    System.out.println("First shuffled list: " + myList);  

    Collections.shuffle(myList);
    System.out.println("Second shuffled list: " + myList);  

		                                 // CONVERTING LIST BACK TO ARRAY
    Object str[] = myList.toArray();
    System.out.print("\nShuffled array: ");  
    for(Object obj : str)
    {
      System.out.print(obj + " ");  
    }
  }
}

Java Shuffle Array shuffle()

     String numbers[] = { "one", "two",  "three", "four", "five", "six" };

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

     List myList = Arrays.asList(numbers);

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.

Collections.shuffle(myList);

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

     Object str[] = myList.toArray();
     System.out.print("\nShuffled array: ");  
     for(Object obj : str)
     {
       System.out.print(obj + " ");  
     }

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 Comment

Your email address will not be published.