Java Collection How to - Randomly shake, shuffle an array to assign new random spots








Question

We would like to know how to randomly shake, shuffle an array to assign new random spots.

Answer

import java.util.Arrays;
import java.util.Random;
//www  .j  a  v  a 2s  .  c  o  m
public class Main {
  public static int[] shuffle(int[] numbers) {
    for (int i = 0; i < numbers.length; i++) {
      int swap = new Random().nextInt(i + 1);
      int temp = numbers[swap];
      numbers[swap] = numbers[i];
      numbers[i] = temp;
    }
    return numbers;
  }
  public static void main(String[] args) {
    int[] i = shuffle(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
    System.out.print(Arrays.toString(i));
  }
}

The code above generates the following result.