Java Method to Shuffle an Array

How to shuffle an array in Java?

There are two approaches to shuffle an int array(randomizes the order of the elements in an array), one is to use the Collections.shuffle() method, the other is to manipulate array elements.

Approach 1: Shuffle elements in an array

This is flexible, and easy to be changed to fit your application.

Input: an int array
Output: shuffled array(in an randomized order)

public static int[] RandomizeArray(int[] array){
		Random rgen = new Random();  // Random number generator			
 
		for (int i=0; i<array.length; i++) {
		    int randomPosition = rgen.nextInt(array.length);
		    int temp = array[i];
		    array[i] = array[randomPosition];
		    array[randomPosition] = temp;
		}
 
		return array;
	}

You can also define a method whose input is a range of the array like below:

Input: range of an int array
Output: randomly shuffled array

For example, given a=1 and b=10, the method returns a shuffled array such as {2 5 6 7 9 8 3 1 10 4}.

public static int[] RandomizeArray(int a, int b){
		Random rgen = new Random();  // Random number generator		
		int size = b-a+1;
		int[] array = new int[size];
 
		for(int i=0; i< size; i++){
			array[i] = a+i;
		}
 
		for (int i=0; i<array.length; i++) {
		    int randomPosition = rgen.nextInt(array.length);
		    int temp = array[i];
		    array[i] = array[randomPosition];
		    array[randomPosition] = temp;
		}
 
		for(int s: array)
			System.out.println(s);
 
		return array;
	}

Approach 2: Java Collection.shuffle() method

// Create an array
Integer[] array = new Integer[]{1, 2, 3, 4};
 
//int[] array = new int[]{1, 2, 3, 4}; //does not work
 
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));
Category >> Real Methods  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Guest

    There’s a problem with approach 2: Arrays.asList takes a variable-length argument list of items to put inside a new list. Since you’re passing ‘array’ as the single argument, a List is created insted, and it contains one item, which is the array. When you then use Collections.shuffle on this new list, it is shuffling a list with one item in it instead of shuffling the Integer objects in the array.

  • in the approach 1: first snippet, there is a possibility that repetitive randomPosition can occur, but got the idea, thanks