How to "shuffle" an array? [duplicate] How to "shuffle" an array? [duplicate] arrays arrays

How to "shuffle" an array? [duplicate]


How about:

List<Card> list =  Arrays.asList(deck);Collections.shuffle(list);

Or one-liner:

Collections.shuffle(Arrays.asList(deck));


One way is to convert the array to a list, and use java.util.Collections.shuffle(array) to shuffle it:

Card[] deck = ...;List<Card> list = Arrays.asList(deck);Collections.shuffle(list);

If you do still need an array instead of a List, you can add:

list.toArray(deck);

Here is a TIO (Try-it-online) link to see the array to list conversion and shuffling in action.

Code of the TIO copied below as reference:

import java.util.Arrays;import java.util.Collections;import java.util.List;class M{  public static void main(String[] a){    // Original array    Integer[] array = new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };    System.out.println("before: " + Arrays.toString(array));    // Convert array to list    List<Integer> list = Arrays.asList(array);    // And shuffle that list    Collections.shuffle(list);    System.out.println("after as list: " + list);    // (Optional) then convert the list back to an array,    // and save it in its initial variable (`array` in this case)    list.toArray(array);    System.out.println("after as array: " + Arrays.toString(array));  }}


I see two ways to do it:

-> You can use a shuffle algorithm like the Fisher-Yates shuffle algorithm if you want to implement yourself the method.

-> You can use the shuffle method from Collections