Computer Science 15-100, Fall 2008
Class Notes:  Getting Started with the Java Collection Framework


  1. ArrayLists
    1. ArrayList Example
    2. ArrayList Methods
      1. add
      2. addAll
      3. clear
      4. contains
      5. get
      6. indexOf
      7. isEmpty
      8. lastIndexOf
      9. remove
      10. set
      11. size
      12. Online ArrayList API
  2. HashSets
    1. HashSet Example
    2. HashSet Methods
      1. add
      2. addAll
      3. clear
      4. contains
      5. isEmpty
      6. remove
      7. size
      8. Online HashSet API
  3. HashMaps
    1. HashMap Example
    2. HashMap Methods
      1. clear
      2. get
      3. isEmpty
      4. keySet
      5. put
      6. remove
      7. size
      8. Online HashMap API
  4. Collections
    1. Collections Example
    2. Collections Methods
      1. binarySearch
      2. reverse
      3. rotate
      4. shuffle
      5. sort
      6. Online Collections API
  5. Arrays (As Lists)
    1. Calling ArrayList.addAll with an Array
    2. Calling Collections Methods with an Array
    3. Using Primitive Arrays as Lists
      1. The Problem:  Arrays.asList Does Not Work with Primitives!
      2. A Solution: intArrayAsList, doubleArrayAsList, ...
  6. Wrapper Classes and Autoboxing
    1. Autoboxing Example
    2. Autoboxing Hazard
  7. Enhanced for Loop
    1. Array Example
    2. ArrayList Example
    3. HashSet Example
    4. HashMap Example
  8. Unchecked versus Checked (with Generics)
  9. Efficiency of the JCF
  10. More Examples
    1. Another ArrayList Example
    2. Another HashSet Example
    3. Another HashMap Example

Getting Started with the JCF (Java Collection Framework)

  1. ArrayLists
     
    1. ArrayList Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("This code demonstrates an ArrayList, which is");
          System.out.println("basically a variable-sized array.");
      
          // Construct an ArrayList
          System.out.println("Calling constructor:");
          ArrayList<String> list = new ArrayList<String>();
      
          // Print (with implicit toString)
          print(list); // see helper method below
      
          // Add elements
          System.out.println("Adding Dog and Cat:");
          list.add("Dog");  // add Dog to end of list
          list.add("Cat");  // add Cat to end of list
          print(list);
      
          // Add an element at a specific location
          System.out.println("Adding Cow at Index 1:");
          list.add(1,"Cow"); // add Cow at index 1
          print(list);
      
          // Add all elements from another collection (such as another list)
          System.out.println("Adding Frog and Bird:");
          ArrayList<String> frogAndBird = new ArrayList<String>();
          frogAndBird.add("Frog");
          frogAndBird.add("Bird");
          list.addAll(frogAndBird); // add all elements from another list
          print(list);
      
          // Add all elements from another list at a specific location
          System.out.println("Adding Frog and Bird again at Index 1:");
          list.addAll(1, frogAndBird); // add all elements at index 1
          print(list);
      
          // Getting and setting a specific element
          System.out.println("Setting element 6 to Cow:");
          System.out.println("  before:  list.get(6) = " + list.get(6));
          list.set(6, "Cow"); // set element at index 6 to "Cow"
          System.out.println("  after:  list.get(6) = " + list.get(6));
          print(list);
      
          // Other accessors (contains, indexOf, lastIndexOf)
          System.out.println("Other accessors:");
          System.out.println("  list.contains(\"Cow\") = " + list.contains("Cow"));
          System.out.println("  list.contains(\"Ant\") = " + list.contains("Ant"));
          System.out.println("  list.indexOf(\"Cow\")  = " + list.indexOf("Cow"));
          System.out.println("  list.indexOf(\"Ant\")  = " + list.indexOf("Ant"));
          System.out.println("  list.lastIndexOf(\"Cow\")  = " + list.lastIndexOf("Cow"));
          System.out.println("  list.lastIndexOf(\"Ant\")  = " + list.lastIndexOf("Ant"));
      
          // remove first occurrence of an element
          System.out.println("Removing first Cow:");
          list.remove("Cow");  // remove first occurrence of "Cow" from list
          print(list);
      
          // remove element at a specific location
          System.out.println("Removing element at index 1:");
          list.remove(1);  // remove element at index 1 from list
          print(list);
      
          // Clear list
          System.out.println("Clearing the list:");
          list.clear(); // clear the list (remove all elements from it)
          print(list);
        }
      
        // Helper method to print the list and some info about it
        public static void print(ArrayList<String> list) {
          System.out.print("  list=" + list.toString());
          System.out.print("  size=" + list.size());
          System.out.print("  isEmpty=" + list.isEmpty());
          System.out.println();
        }
      }
    2. ArrayList Methods
       
      1. add
        list.add(value);        // add value to end of list
        list.add(index, value); // add value at the given index
         
      2. addAll
        list.addAll(otherList);        // add all elements from another list
        list.addAll(index, otherList); // add all elements at the given index

         
      3. clear
        list.clear(); // clear the list (remove all elements from it)
         
      4. contains
        list.contains(value)  // return true if the list contains the value, false otherwise
         
      5. get
        list.get(index);  // return the element at the given index
         
      6. indexOf
        list.indexOf(value); // return first index of given value, or -1 if not in list
         
      7. isEmpty
        list.isEmpty();  // return true if list is empty (size 0), or false otherwise
         
      8. lastIndexOf
        list.lastIndexOf(value); // return last index of given value, or -1 if not in list
         
      9. remove
        list.remove(value);  // remove first occurrence of value from list
        list.remove(index);  // remove element at the given index from list

         
      10. set
        list.set(index, value); // set element at given index to value
         
      11. size
        list.size(); // return the size of the list (# of elements in the list)
         
      12. Online ArrayList API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html

         
  2. HashSets
     
    1. HashSet Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("This code demonstrates a HashSet, which is");
          System.out.println("similar to an ArrayList, except that it may not");
          System.out.println("contain two copies of equal values, and there is");
          System.out.println("no guarantee of the order of the set's elements.");
      
          // Construct a HashSet
          System.out.println("Calling constructor:");
          HashSet<String> set = new HashSet<String>();
      
          // Print (with implicit toString)
          print(set); // see helper method below
      
          // Add elements
          System.out.println("Adding Dog and Cat:");
          set.add("Dog");  // add Dog to set
          set.add("Cat");  // add Cat to set
          print(set);
      
          // Add elements with duplicates
          System.out.println("Adding Frog and Cat:");
          set.add("Frog");  // add Frog to set
          set.add("Cat");   // add Cat to set
          print(set);
      
          // Add all elements from another collection (say, a list)
          System.out.println("Adding Frog and Bird:");
          ArrayList<String> frogAndBird = new ArrayList<String>();
          frogAndBird.add("Frog");
          frogAndBird.add("Bird");
          set.addAll(frogAndBird); // add all elements from a list
          print(set);
      
          // Other accessors (just contains):
          System.out.println("Other accessors (just contains):");
          System.out.println("  set.contains(\"Dog\") = " + set.contains("Dog"));
          System.out.println("  set.contains(\"Ant\") = " + set.contains("Ant"));
      
          // remove an element
          System.out.println("Removing Dog:");
          set.remove("Dog");  // remove "Dog" from set
          print(set);
      
          // Clear set
          System.out.println("Clearing the set:");
          set.clear(); // clear the list (remove all elements from it)
          print(set);
        }
      
        // Helper method to print the list and some info about it
        public static void print(HashSet<String> set) {
          System.out.print("  set=" + set.toString());
          System.out.print("  size=" + set.size());
          System.out.print("  isEmpty=" + set.isEmpty());
          System.out.println();
        }
      }
    2. HashSet Methods
       
      1. add
        set.add(value);  // add value to the set if not already present
         
      2. addAll
        set.addAll(list); // add all elements from the list to the set
         
      3. clear
        set.clear(); // clear the set (remove all elements from it)
         
      4. contains
        set.contains(value)  // return true if the set contains the value, false otherwise
         
      5. isEmpty
        set.isEmpty();  // return true if set is empty (size 0), or false otherwise
         
      6. remove
        set.remove(value);  // remove value from set
         
      7. size
        set.size(); // return the size of the set (# of elements in the set)
         
      8. Online HashSet API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashSet.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html

         
  3. HashMaps
     
    1. HashMap Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("This code demonstrates a HashMap, which maps");
          System.out.println("keys to values.  Note that the keys form a Set,");
          System.out.println("which means the map cannot contain two copies");
          System.out.println("of equal keys, and there are no guarantees");
          System.out.println("of the order in which keys occur.");
          System.out.println();
      
          // Construct a HashMap
          System.out.println("Calling constructor:");
          HashMap<String, String> map = new HashMap<String, String>();
      
          // Print (with implicit toString)
          print(map); // see helper method below
      
          // Add elements (key-value pairs)
          System.out.println("Mapping Paris to Texas, and Ankara to Turkey:");
          map.put("Paris", "Texas");
          map.put("Ankara", "Turkey");
          print(map);
      
          // Add elements with duplicate keys
          System.out.println("Mapping Paris to France, and Doha to Qatar:");
          map.put("Paris", "France");
          map.put("Doha", "Qatar");
          print(map);
      
          // Other accessors (get, containsKey, and keySet):
          System.out.println("Other accessors (get and containsKey):");
          System.out.println("  map.get(\"Paris\") = " + map.get("Paris"));
          System.out.println("  map.get(\"London\") = " + map.get("London"));
          System.out.println("  map.containsKey(\"Paris\") = " + map.containsKey("Paris"));
          System.out.println("  map.containsKey(\"London\") = " + map.containsKey("London"));
          System.out.println("  map.keySet() = " + map.keySet());
      
          // remove a key (and its mapped value)
          System.out.println("Removing Paris:");
          map.remove("Paris");  // remove "Paris" key (and its value) from map
          print(map);
      
          // Clear map
          System.out.println("Clearing the map:");
          map.clear(); // clear the map (remove all key-value pairs from it)
          print(map);
        }
      
        // Helper method to print the list and some info about it
        public static void print(HashMap<String, String> map) {
          System.out.print("  map=" + map.toString());
          System.out.print("  map=" + map.size());
          System.out.print("  isEmpty=" + map.isEmpty());
          System.out.println();
        }
      }
    2. HashMap Methods
       
      1. clear
        map.clear(); // remove all key-value entries from the hashMap
         
      2. get
        map.get(key); // return the value this key maps to, or null if not in map.
         
      3. isEmpty
        map.isEmpty(); // return true if the map is empty (size 0), false otherwise
         
      4. keySet
        map.keySet(); // return a Set containing all the keys in this map
         
      5. put
        map.put(key, value); // map the given key to the given value
         
      6. remove
        map.remove(key); // remove the key (and its mapped value, if any) from the map
         
      7. size
        map.size(); // return the size of the map (# of key-value pairs in the map)
         
      8. Online HashMap API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html

         
  4. Collections
     
    1. Collections Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("This code demonstrates static methods from the");
          System.out.println("Collections class, which provides helpful utilities");
          System.out.println("for Lists (and other Collections) in the same way");
          System.out.println("that the Arrays class does for arrays.");
          System.out.println();
      
          // Construct an ArrayList and add some values
          System.out.println("Constructing a list and adding Dow, Cow, and Bird");
          ArrayList<String> list = new ArrayList<String>();
          list.add("Cow");
          list.add("Dog");
          list.add("Bird");
          list.add("Ant");
          print(list);
      
          // First test of (broken) binarySearch over unsorted list
          System.out.println("Broken binarySearch in unsorted list:");
          System.out.println("  Collections.binarySearch(\"Ant\") = " +
                                Collections.binarySearch(list, "Ant"));
      
          // Sort the list
          System.out.println("Sorting the list:");
          Collections.sort(list);
          print(list);
      
          // Second test of (working) binarySearch over sorted list
          System.out.println("Working binarySearch in sorted list:");
          System.out.println("  Collections.binarySearch(\"Ant\") = " +
                                Collections.binarySearch(list, "Ant"));
          System.out.println("  Collections.binarySearch(\"Frog\") = " +
                                Collections.binarySearch(list, "Frog"));
      
          // Reverse the list
          System.out.println("Reversing the list:");
          Collections.reverse(list);
          print(list);
      
          // Rotate the list
          System.out.println("Rotating the list 1 to the right:");
          Collections.rotate(list, 1);
          print(list);
          System.out.println("Rotating the list 3 to the right:");
          Collections.rotate(list, 3);
          print(list);
      
          // Shuffle the list
          System.out.println("Shuffling the list a few times:");
          Collections.shuffle(list);
          print(list);
          Collections.shuffle(list);
          print(list);
          Collections.shuffle(list);
          print(list);
        }
      
        // Helper method to print the list and some info about it
        public static void print(ArrayList<String> list) {
          System.out.println("  list=" + list.toString());
        }
      }
    2. Collections Methods
       
      1. binarySearch
        Collections.binarySearch(list, value); // Assuming list is sorted, perform binary
                                               // search and return the index of the value
                                               // or -1 if it is not in the list.

         
      2. reverse
        Collections.reverse(list); // Reverse the list, so [1, 2, 3] becomes [3, 2, 1]
         
      3. rotate
        Collections.rotate(list, distance); // Rotate the list to the right by the given
                                            // distance.  So rotating [1, 2, 3, 4] two to
                                            // the right becomes [3, 4, 1, 2]
      4. shuffle
        Collections.shuffle(list); // Shuffle the list into a random order
         
      5. sort
        Collections.sort(list); // Sort the list
         
      6. Online Collections API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html

         
  5. Arrays (As Lists)
     
    1. Calling ArrayList.addAll with an Array

      Failed Attempt
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          ArrayList<String> list = new ArrayList<String>();
          list.add("Fred");
          System.out.println(list);
      
          String[] moreNames = { "Wilma", "Barney", "Betty" };
          // try (and fail) to add all the names in the array to the list
          list.addAll(moreNames);  // will not compile!
          System.out.println(list);
        }
      }

      Fixed With Arrays.asList

      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          ArrayList<String> list = new ArrayList<String>();
          list.add("Fred");
          System.out.println(list);
      
          String[] moreNames = { "Wilma", "Barney", "Betty" };
          // Add all the names in the array to the list
          list.addAll(Arrays.asList(moreNames));  // works!
          System.out.println(list);
        }
      }
    2. Calling Collections Methods with an Array
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("Demo calling some of the Collections methods");
          System.out.println("using an array and Arrays.asList.  This demo shows");
          System.out.println("just a few methods, but the technique works in general.");
          System.out.println();
      
          String[] a = { "Fred", "Wilma", "Barney", "Betty" };
      
          System.out.print("Using List's toString method:");
          System.out.println(Arrays.asList(a));
      
          System.out.print("Max value in array: " );
          System.out.println(Collections.max(Arrays.asList(a)));
      
          System.out.print("Min value in array: ");
          System.out.println(Collections.min(Arrays.asList(a)));
      
          System.out.print("Reversed array:");
          Collections.reverse(Arrays.asList(a));
          System.out.println(Arrays.asList(a));
      
          System.out.print("Verify we modified the actual array: ");
          System.out.println(Arrays.toString(a));
        }
      }
    3. Using Primitive Arrays as Lists
       
      1. The Problem:  Arrays.asList Does Not Work with Primitives!
        import java.util.*;
        class MyCode  {
          public static void main(String[]args){
            int[] a = {1, 2, 3};
            Collections.reverse(Arrays.asList(a));  // Fails!!! (quietly, too)
            System.out.println(Arrays.toString(a));
        
            Integer[] b = {1, 2, 3};
            Collections.reverse(Arrays.asList(b));  // Works!!!
            System.out.println(Arrays.toString(b));
          }
        }
      2. A Solution:  intArrayAsList, doubleArrayAsList, ...
        import java.util.*;
        class MyCode  {
        
          // Helper method to support using int arrays as Lists
          public static List<Integer> intArrayAsList(final int[] a) {
            return new AbstractList<Integer>() {
              public Integer get(int i) { return a[i]; }
              public Integer set(int i, Integer val) { int old=a[i]; a[i]=val; return old;}
              public int size() { return a.length; }
            };
          }
        
          public static void main(String[]args){
            int[] a = {1, 2, 3};
            Collections.reverse(intArrayAsList(a));  // Works with helper method!
            System.out.println(Arrays.toString(a));
        
            Integer[] b = {1, 2, 3};
            Collections.reverse(Arrays.asList(b));  // Still works!!!
            System.out.println(Arrays.toString(b));
          }
        }
        
        Another Example (for doubles):
        
        import java.util.*;
        class MyCode  {
        
          // Helper method to support using int arrays as Lists
          public static List<Double> doubleArrayAsList(final double[] a) {
            return new AbstractList<Double>() {
              public Double get(int i) { return a[i]; }
              public Double set(int i, Double val) { double old=a[i]; a[i]=val; return old;}
              public int size() { return a.length; }
            };
          }
        
          public static void main(String[]args){
            double[] a = {1.2, 3.4, 5.6};
            Collections.reverse(doubleArrayAsList(a));  // Works with helper method!
            System.out.println(Arrays.toString(a));
        
            Double[] b = {1.2, 3.4, 5.6};
            Collections.reverse(Arrays.asList(b));  // Still works!!!
            System.out.println(Arrays.toString(b));
          }
        }
  6. Wrapper Classes and Autoboxing
     
    1. Autoboxing Example

      Failed Attempt
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          // try (and fail) to create an ArrayList of int's
          ArrayList<int> list = new ArrayList<int>(); // will not compile!
          list.add(1);
          list.add(2);
          list.add(3);
          System.out.println(list);
        }
      }

      Fixed with Wrapper Class and Autoboxing:

      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          // Create an ArrayList of Integers (Wrapper Class for ints)
          ArrayList<Integer> list = new ArrayList<Integer>(); // works!
          list.add(1); // Autoboxes 1 to Wrapper Class instance: new Integer(1)
          list.add(2);
          list.add(3);
          System.out.println(list);
        }
      }
    2. Autoboxing Hazard
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("Demo showing the hazards of autoboxing.");
      
          ArrayList<Integer> list = new ArrayList<Integer>();
          list.add(1234);
          list.add(1234);
          System.out.println("Original list: " + list);
      
          System.out.println("\nAll the following should be true:");
          System.out.println(list.get(0) == 1234); // works
          System.out.println(list.get(1) == 1234); // works
          System.out.println(list.get(0) == list.get(1)); // fails!
      
          System.out.println("\nNow the following WILL be true:");
          int i0 = list.get(0);
          int i1 = list.get(1);
          System.out.println(i0 == 1234); // works
          System.out.println(i1 == 1234); // works
          System.out.println(i0 == i1);   // also works!
          System.out.println();
      
          System.out.println("Moral: only use autoboxing when necessary, and use");
          System.out.println("real primitives (ints, doubles, etc) for all arithmetic!");
        }
      }
  7. Enhanced for Loop
     
    1. Array Example
      class MyCode  {
        public static void main(String[] args) {
          String[] array = { "Steelers", "Penguins", "Pirates" };
      
          System.out.println("Traversing array using an enhanced for loop:");
          for (String s : array)
            System.out.println(s);
        }
      }
    2. ArrayList Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          ArrayList<String> list = new ArrayList<String>();
          list.add("Larry");
          list.add("Moe");
          list.add("Larry");
          list.add("Curly");
      
          System.out.println("Traversing list using an enhanced for loop:");
          for (String s : list)
            System.out.println(s);
        }
      }
    3. HashSet Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          HashSet<String> set = new HashSet<String>();
          set.add("Larry");
          set.add("Moe");
          set.add("Larry"); // duplicate is effectively ignored
          set.add("Curly");
      
          System.out.println("Traversing set using an enhanced for loop:");
          for (String s : set)
            System.out.println(s);
        }
      }
    4. HashMap Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          HashMap<String, String> map = new HashMap<String, String>();
          map.put("Paris", "France");
          map.put("Ankara", "Turkey");
          map.put("Doha", "Qatar");
      
          System.out.println("Traversing map KEYS using an enhanced for loop:");
          for (String key : map.keySet())
            System.out.println(key);
      
          System.out.println();
      
          System.out.println("Traversing map KEY-VALUE PAIRS using an enhanced for loop:");
          for (String key : map.keySet())
            System.out.println(key + ", " + map.get(key));
        }
      }
  8. Unchecked versus Checked (with Generics)

    Checked with Generics (New Style)
    import java.util.*;
    class MyCode  {
      public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Douglas Adams");
        String name = list.get(0);
        System.out.println(name);
    
        HashSet<String> set = new HashSet<String>();
        set.add("Blaise Pascal");
        boolean blaiseIsThere = set.contains("Blaise Pascal");
        System.out.println(blaiseIsThere);
    
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("Denver", "sunny");
        String weatherInDenver = map.get("Denver");
        System.out.println(weatherInDenver);
      }
    }

    Unchecked (Old Style)

    import java.util.*;
    @SuppressWarnings("unchecked")
    class MyCode  {
      public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("Douglas Adams");
        String name = (String) list.get(0);
        System.out.println(name);
    
        HashSet set = new HashSet();
        set.add("Blaise Pascal");
        boolean blaiseIsThere = set.contains("Blaise Pascal");
        System.out.println(blaiseIsThere);
    
        HashMap map = new HashMap();
        map.put("Denver", "sunny");
        String weatherInDenver = (String) map.get("Denver");
        System.out.println(weatherInDenver);
      }
    }
  9. Efficiency of the JCF
    import java.util.*;
    class MyCode  {
      public static void main(String[] args) {
        System.out.println("Demo showing efficiency of the JCF.");
        int n = 25000;
    
        System.out.print("Add " + n + " elements using arrays:  ");
        long time0 = System.currentTimeMillis();
        int[] array = new int[0];
        for (int i=0; i<n; i++)
          array = add(array, i);
        assert(array.length == n);
        long time1 = System.currentTimeMillis();
        int elapsedTime = (int) (time1 - time0);
        System.out.println(elapsedTime + " ms");
    
        System.out.print("Add " + n + " elements using an ArrayList:  ");
        time0 = System.currentTimeMillis();
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<n; i++)
          list.add(i);
        assert(list.size() == n);
        time1 = System.currentTimeMillis();
        elapsedTime = (int) (time1 - time0);
        System.out.println(elapsedTime + " ms");
      }
    
      // From class notes on 1d-arrays:
      public static int[] add(int[] a, int newValue) {
        int[] result = new int[a.length+1];
        for (int i=0; i<a.length; i++)
          result[i] = a[i];
        result[a.length] = newValue;
        return result;
      }
    }
  10. More Examples
     
    1. Another ArrayList Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("Enter a list of words (sentinel = 'end'):");
          Scanner scanner = new Scanner(System.in);
          String next;
      
          // ArrayList<String> is like a variable-sized String[]
          ArrayList<String> list = new ArrayList<String>();
      
          while (! (next = scanner.next()).equals("end"))
            list.add(next);
      
          System.out.println();
          System.out.println("Here are all the words you entered:");
          System.out.println(list);
          System.out.println();
      
          System.out.println("Here is every-other-word:");
          for (int i=0; i<list.size(); i+=2)
            System.out.print(list.get(i) + " ");
          System.out.println("\n");
      
          System.out.println("Here they are in reverse:");
          Collections.reverse(list);
          System.out.println(list);
          System.out.println();
      
          System.out.println("And here they are sorted:");
          Collections.sort(list);
          System.out.println(list);
          System.out.println();
        }
      }
    2. Another HashSet Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("Enter a list of words with some DUPLICATES (sentinel = 'end'):");
          Scanner scanner = new Scanner(System.in);
          String next;
      
          // HashSets are like Lists but WITHOUT DUPLICATES
          HashSet<String> set = new HashSet<String>();
      
          while (! (next = scanner.next()).equals("end"))
            set.add(next);
      
          System.out.println();
          System.out.println("Here are all the UNIQUE words you entered:");
          System.out.println(set);
          System.out.println();
      
          System.out.println("Now enter some words to see if they are in the first list:");
          String key;
          while (! (key = scanner.next()).equals("end")) {
            if (set.contains(key))
              System.out.println(key + " is in the original set.");
            else
              System.out.println(key + " is NOT in the original set");
          }
        }
      }
    3. Another HashMap Example
      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          System.out.println("Enter key-value PAIRS of words (sentinel = 'end'):");
          Scanner scanner = new Scanner(System.in);
          String nextKey, nextValue;
      
          // A HashMap maps keys to values
          HashMap<String, String> map = new HashMap<String, String>();
      
          while (! (nextKey = scanner.next()).equals("end")) {
            nextValue = scanner.next();
            map.put(nextKey, nextValue);
          }
      
          System.out.println();
          System.out.println("Here is the map you entered:");
          System.out.println(map);
          System.out.println();
      
          System.out.println("Now enter some words to see what they map to:");
          String key;
          while (! (key = scanner.next()).equals("end")) {
            String value = map.get(key);
            if (value == null)
              System.out.println(key + " is NOT in the original map");
            else
              System.out.println(key + " maps to " + value);
          }
        }
      }

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem