How to shuffle an array in Java

By | December 4, 2018

Today we will create an static method which can shuffle an array in java. The array can be Long, Integer, String or any valid object type.

Technology Advanced Programming

public static <T> void shuffleArray(T[] ar){
  // If running on Java 6 or older, use `new Random()` on RHS here
  Random rnd = new Random();
  for (int i = ar.length-1; i >0; i--){
    int index = rnd.nextInt(i +1);
    // Simple swap
    T a= ar[index];
    ar[index] = ar[i];
    ar[i] = a;
Lets discuss a little what we are doing here. In the first line we described <T> void as the return type of the function. Also, by <T> we are meaning that it can be any object type. But not a variable type. The objects can be like Long, Integer, String etc. Now we create a new instance of Random by calling new Random(). Next we are iterating the whole array. While iterating we are swapping with random indexes.
The usage will be as follows:
Long[] r = new Long[100]
// Or put values in your own way
//Now shuffle it
Note that, we used Long data type not long. The array must be a java object type, not a variable.