Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

Shuffle an Array or a List - Algorithm in Java

Lars Vogel

Version 0.1

17.05.2009

Revision History
Revision 0.117.05.2009Lars Vogel
Created

Abstract

This article describes how to shuffle the content of an array or a list in Java. After the shuffle the elements in the array or the list are randomly sorted.


Table of Contents

1. Shuffle an array with the Collections framework
2. Implementation in Java
3. Thank you
4. Questions and Discussion
5. Links and Literature
5.1. Source Code
5.2. General

1. Shuffle an array with the Collections framework

An array or an java.util.list contains a sorted list of values. Shuffling an array or a list means that you are randomly re-arranging the content of that structure. Have you wondered how you could shuffle an array or a list without the collection framework? This article demonstrates how the shuffling works so that you can learn how the standard libraries might do this.

Tip

If you only interested in shuffling with the collections framework you should of course use the standard Java. Use Collections.shuffle(list) to shuffle a list with the standard Java library or Collections.shuffle(Arrays.asList(a)) to shuffle an array a.

The approach works independent of the content of the array or the list.

The shuffle is random as the algorithm by selecting uniformly en element which has not been selected. For example if the element at position 2 is selected it can be exchanged with all elements at position 2 until position n-1 (as the list /array has 0 - n-1 positions).