How do I shuffle elements of an array?

Category: java.util, viewed: 10499 time(s).
package org.kodejava.example.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayShuffle {
	public static void main(String[] args) {
		// Initialize the contents of our array
		String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
		
		// As the Collections.shuffle method need a list for the parameter we
		// convert our array into List using the Arrays class.
		List<String> list = Arrays.asList(alphabets);
		
		// Here we just simply used the shuffle method of Collections class
		// to shuffle out defined array.
		Collections.shuffle(list);
		
		// Run the code again and again, then you'll see how simple we do shuffling
		for (String alpha : list) {
			System.out.print(alpha + " ");
		}
	}
}

Some of the generated results are:

F E C A G B H I J D 
D A H E B G I J C F 
A E H J D B C I F G 
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats