import java.util.Arrays; import java.util.Random; /* There is normally no need to write shuffle. There is a static method void Collections.shuffle (List<?> list, Random rng) in the java.util.Collections class, but not one in java.util.Arrays. In the case of an array one can use: List<T> Arrays.asList(T... a) */ public final class GenericShuffle { private static final Random RNG = new Random (Long.getLong ("seed", System.nanoTime())); // Randomly permute the elements of the array 'x' public static <T> void shuffle (final T[] x) { final int n = x.length; for (int i = 0; i<n-1; i++) { // Randomly select a position in the range i..n-1 final int j = i + RNG.nextInt (n-i); // Swap elements at position i and j final T t = x[j]; x[j] = x[i]; x[i] = t; } } public static void main (final String[] args) { System.out.println (Arrays.toString (args)); shuffle (args); System.out.println (Arrays.toString (args)); } }