An Array in Java is a collection of elements of same Data type or Object type. The array has a fixed length. ArrayList, on the other hand, can hold any number of elements because of its variable size at runtime. Shuffling is also called Randomizing elements. Let us know how to Shuffle elements in an Array or ArrayList or List using Java programming.
Shuffle Elements in Array in Java | Randomizing Elements
The meaning of Shuffle is to change the position of each element in the Array or ArrayList to a random position. You can use the code snippets in Android too. Java code example is given below.
import java.util.Random; public class ShuffleArrayElements { public static void main(String[] args) { String strAry[] = {"CAR", "BUS", "TRUCK", "TRACTOR", "SCOOTER", "TRAIN"}; String strNewAry[] = new String[strAry.length]; int strIndex[] = new int[strAry.length]; Random random = new Random(); for(int i=0; i<strIndex.length; i++) { strIndex[i] = -1; } for(int i=0; i<strIndex.length; i++) { int index = -1; if(i==0) { index=random.nextInt(strIndex.length); } else { while( containsIndex(index=random.nextInt(strIndex.length), strIndex)) { //nothing. index holds unique index. } } strIndex[i]= index; strNewAry[i] = strAry[strIndex[i]]; System.out.println(strAry[strIndex[i]]); } } static boolean containsIndex(int i, int[] ary) { for(int j=0; j<ary.length; j++) { if(i == ary[j]) { return true; } } return false; } }
Shuffle Elements in ArrayList or List in Java | Randomizing Elements
Java code example is given below. It shuffles elements in the ArrayList or List. We have not used any methods of Collections library. We have not even used "contains()" method of ArrayList collection.
import java.util.Random; import java.util.ArrayList; public class ShuffleArrayListElements { public static void main(String[] args) { //String strAry[] = {"CAR", "BUS", "TRUCK", "TRACTOR", "SCOOTER", "TRAIN"}; ArrayList<String> list = new ArrayList<String>(); list.add("CAT"); list.add("DOG"); list.add("FOX"); list.add("RABBIT"); list.add("PIG"); list.add("DEER"); ArrayList<String> newList = new ArrayList<String>(); int strIndex[] = new int[list.size()]; Random random = new Random(); for(int i=0; i<strIndex.length; i++) { strIndex[i] = -1; } for(int i=0; i<strIndex.length; i++) { int index = -1; if(i==0) { index=random.nextInt(strIndex.length); } else { while( containsIndex(index=random.nextInt(strIndex.length), strIndex)) { //nothing. index holds unique index. } } strIndex[i]= index; newList.add(list.get(index)); System.out.println(newList.get(i)); } } static boolean containsIndex(int i, int[] ary) { for(int j=0; j<ary.length; j++) { if(i == ary[j]) { return true; } } return false; } }
You can use ArrayList "contains" method instead of using containsIndex() method.
while( list.contains(list.get(index=random.nextInt(strIndex.length)))) { //nothing. index holds unique index. }
In case you missed, check below program on Array and ArrayList.