How to Randomise an ArrayList in Java


Here this tutorial will show us how to shuffle ArrayList with the methods in collections.shuffle (), as shown below.

Source Code

package com.beginner.examples;

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

public class ShuffleArrayListExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList numList=new ArrayList();
		//add elements
		numList.add(5);
		numList.add(6);
		numList.add(7);
		numList.add(8);
		System.out.println(numList);
		//Shuffle numlist
		Collections.shuffle(numList);
		
		System.out.println("After the shuffle"+numList);
		//
		Collections.shuffle(numList);
		
		System.out.println("After the shuffle"+numList);
		
		
	}

}

Output:

[5, 6, 7, 8]
After the shuffle[5, 8, 6, 7]
After the shuffle[5, 6, 8, 7]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments