Nov 27

Sometimes we need to shuffle the oder of elements in a list or array, like shuffling a deck of cards. The Collections utility class has a shuffle() method that achieves this for List’s, but what about arrays. There is no corresponding shuffle() method in the Arrays class, surely we don’t need to loop through the array.

Turns out the solution is very simple. We can just use the same method we use for shuffling lists after first creating a List representation of our array using Arrays.asList()

String[] array = {"A", "B", "C", "D", "E"};
Collections.shuffle(Arrays.asList(array));
System.out.println(Arrays.toString(array));

written by objects \\ tags: , , , ,


Leave a Reply

You must be logged in to post a comment.