Source of Shuffle.java


  1: //Shuffle.java
  2: //Illustrates use of the java.util.Collections.shuffle() method.

  4: import java.util.ArrayList;
  5: import java.util.Arrays;
  6: import java.util.Collections;
  7: import java.util.Random;

  9: public class Shuffle
 10: {
 11:     public static void main(String[] args)
 12:     {
 13:         ArrayList<Integer> integers = new ArrayList<>();
 14:         for (int i = 1; i <= 10; i++)
 15:         {
 16:             integers.add(i);
 17:         }
 18:         for (int i : integers)
 19:         {
 20:             System.out.print(i + " ");
 21:         }
 22:         System.out.println();

 24:         //Activate one of the following lines of code before running
 25:         //This first code line gives different values on each run
 26:         // Collections.shuffle(integers);
 27:         //This second code line gives different values on each run
 28:         // Collections.shuffle(integers, new Random(10));
 29:         for (int i : integers)
 30:         {
 31:             System.out.print(i + " ");
 32:         }
 33:         System.out.println();

 35:         String[] shortNamesArray =
 36:         {
 37:             "Ace", "Ada", "Ali", "Amy", "Ann", "Art", "Ava", "Bea",
 38:             "Ben", "Bob", "Boz", "Cal", "Cam", "Dag", "Dan", "Deb",
 39:             "Don", "Dot", "Eva", "Eve", "Fay", "Gil", "Guy", "Hal",
 40:             "Ian", "Jan", "Jim", "Joe", "Kay", "Ken", "Kim", "Liz",
 41:             "Mac", "Nan", "Ora", "Pam", "Red", "Rex", "Rik", "Rip",
 42:             "Rob", "Rod", "Ron", "Roy", "Sam", "Tim", "Tom", "Uma",
 43:             "Val", "Wes"
 44:         };
 45:         //Look at how easy it is to put an array into an ArrayList
 46:         ArrayList<String> shortNamesList
 47:             = new ArrayList<>(Arrays.asList(shortNamesArray));
 48:         for (int i = 0; i < shortNamesList.size(); i++)
 49:         {
 50:             if (i % 10 == 0)
 51:             {
 52:                 System.out.println();
 53:             }
 54:             System.out.print(shortNamesList.get(i) + " ");
 55:         }
 56:         System.out.println();

 58:         //Activate one of the following lines of code before running ...
 59:         //This first line of code will give different values on each run
 60:         // Collections.shuffle(shortNamesList);
 61:         //This second line of code will give the same values on each run
 62:         // Collections.shuffle(shortNamesList, new Random(10));
 63:         for (int i = 0; i < shortNamesList.size(); i++)
 64:         {
 65:             if (i % 10 == 0)
 66:             {
 67:                 System.out.println();
 68:             }
 69:             System.out.print(shortNamesList.get(i) + " ");
 70:         }
 71:         System.out.println();
 72:     }
 73: }