Shuffle an array of type T - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Shuffle an array of type T

Demo Code


//package com.java2s;

public class Main {
    /**// w w  w  .  j ava 2 s .c  o m
     * Shuffle an array of type T
     *
     * @param <T> The type contained in the array
     * @param array The array to be shuffled
     */
    public static <T> void shuffle(T[] array) {
        for (int i = array.length; i > 1; i--) {
            T temp = array[i - 1];
            int randIx = (int) (Math.random() * i);
            array[i - 1] = array[randIx];
            array[randIx] = temp;
        }
    }
}

Related Tutorials