Collections Classes
Practical Examples Notes

( to accompany web site, to use in lecture)
http://logos.cs.uic.edu/340%20Notes/JavaProgramming/Collections.html

Practical Examples (Do with Netbeans)

GradesArrayList

  1. Illustrate adding a Bean Pattern to StudentTest class for String name, int score
  2. Read input from file and echo it (illustrate need for toString() to give output that makes sense
  3. Go through array values, accumulating scores into sum for calculation of the average
    If using NetBeans, note that explicit pathname to file must be given.
  4. Implement Comparable interface.
    Will need to define compareTo(), after which presto you can call Collection.sort( theArrayList)
    [Then leave this off of example to continue below, so issue of needing it again arises when we get down to TreeSet]

GradesHashSet

  1. First look at the example description for HashSet. Note how it works fine. Let's try and do it ourselves.
  2. Change constructor from ArrayList instance = new ArrayList();
         to
    Set instance = new HashSet();
    Ensure imports are given for java.util.HashSet
  3. The code to traverse ArrayList will no longer work, since ArrayList.get(i) is now not defined. Instead, we must use an iterator
  4. To do this, first import java.util.Iterator;
    Next add the iterator code to accumulate sum of scores for average score calculation. Note that within the code that displays the studentTest and then retrieves the test score, iterator.next() should only be called once, otherwise it will advance past elements. To use it twice use a reference to store it.
  5. Implement hashCode(), so system knows where to store each StudentTest. First implement hashCode() using only the name.
    Note that the same name all map to the same bucket. Now change hashCode() so that it also uses score as part of the hash. Now the same name (but different score) map to different buckets.
  6. Note that duplicate input values are still being stored. Why? Didn't the example shown on web page not store the duplicates?
    (Answer: since we haven't implemented the equals() method, the system can't compare items to see if they are duplicates.)
    We must implement equals() to eliminate duplicates.
    If we implement equals() but not hashmap(), it doesn't work, since hashmap() gets called first
  7. See Bloch book, pp. 38-39 on how to write a good hashcode()
    1. Do not omit significant parts in computing hashcode for the sake of efficiency: Java String previous to v. 1.2 did this & then had problems with long URLs (Bloch, p. 41)
    2. equal objects must have equal hashcodes

GradesTreeSet

  1. Make copy of previous files into a new package. Add the code for importing java.util.TreeSet.
  2. After the old call to printCollection(), create a TreeSet based on the existing HashSet
         Set sortedSet = new TreeSet( scores);
    and again call printCollection();
  3. Pay careful attention to the resulting compiler error and look at the stack trace, which ends up at a call to compare()
    For this code to work we must implement interface Comparable & have method compareTo(). Note that if we have the right method, but do not implement interface Comparable, it still doesn't work (try it and follow the stack trace to see the requirement of the interface existing).

GradesHashMap

  1. Ensure imports for java.util.HashMap and java.util.Map (maybe just use java.util.*)
  2. Change declaration of data structures to be
         Map scores = new HashMap()
  3. To build data structure, to add to the HashMap we must use put() as in:
         scores.put( aTest.getName(), new Integer(aTest.getScore()) );
  4. To iterate through data structure we can use
            for (Iterator iterator=scores.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry e = (Map.Entry) iterator.next();
                sum += ((Integer)e.getValue()).intValue();
            }
    
  5. And similarly also modify the printCollection() method.
    Note that an alternative to iterating through the Map to print it is to simply use
          System.out.println( theMap); // where theMap is a Map
  6. Add code to create a TreeMap from the HashMap, then again call printCollection() to show output is now in sorted order.