How to Shuffle ArrayList Elements in Java


In following example, let us see how to shuffle elements of ArrayList object with shuffle method of Collections class in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.Collections;

public class ShuffleArrayListElementsExample {

	
	public static void main(String[] args) {
	
		ArrayList al = new ArrayList();
		
		al.add("1");
		al.add("2");
		al.add("3");
		al.add("4");
		al.add("5");
		al.add("6");
		
		Collections.shuffle(al);
		System.out.println("First shuffle:"+al);
		
		Collections.shuffle(al);
		System.out.println("The second shuffle:"+al);

	}

}

Output:

First shuffle:[6, 5, 4, 3, 2, 1]
The second shuffle:[5, 3, 4, 1, 6, 2]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments