Here is a single line code that lets you shuffle elements in an ArrayList. The method shuffle() in the Collections class lets you do this. Note that the line you write is no more than single line, there are a lot of lines written in the shuffle() method
import java.util.*;
class ShuffleElements {
public static void main(String args[]) {
// Do nothing, if no arguments < 2
if (args.length < 2) return;
// Create an array list containing the array
// Arrays.asList() adds the given array to a List
// and returns that object
// The second constructor of ArrayList
ArrayList < String > a = new ArrayList < > (Arrays.asList(args));
// Shuffle the elements
Collections.shuffle(a);
// Print all of them
for (int i = 0; i < args.length; i++) {
System.out.println(a.get(i));
}
}
}
No comments:
Post a Comment