cs230 Lecture Notes Week 11 Friday Homework 9 solutions -------------------- Guardian patterns A good one (from main in Sort.java) if (args.length == 0 || args[0] == null || args[0].length() == 0) { c = 's'; } else { c = args[0].charAt(0); } A not so good one (from merge in Sort.java) if (i == a1.length || j != a2.length && a2[j] > a1[i]) { result[k] = a2[j]; j++; } else { result[k] = a1[i]; i++; } Homework 10 ----------- Key, Value, Key-Value pair Keys are unique -- values are not necessarily. Example: count the frequency of the words in a file public void processWord (String word) { Integer i = (Integer) ht.get (word); if (i == null) { ht.put (word, new Integer (1)); } else { Integer j = new Integer (i.intValue() + 1); ht.put (word, j); } } How do we traverse the entries in a table? The keys method returns an Enumeration! (just like an Iterator -- left over from previous) Enumeration enum = ht.keys (); while (enum.hasMoreElements ()) { String key = (String) enum.nextElement (); How do we find the top 20? class Pair implements Comparable { String s, Integer w; } Table implementation -------------------- class KeyValuePair { Object key, value; public KeyValuePair (Object key, Object value) { this.key = key; this.value = value; } public String toString () { return "{ " + key + ", " + value + " }"; } } Vector implementation of a Table public class Table { Vector v; public void put (Object key, Object value) { KeyValuePair pair = new KeyValuePair (key, value); v.add (pair); } public Object get (Object key) { Iterator iterator = v.iterator (); while (iterator.hasNext ()) { KeyValuePair pair = (KeyValuePair) iterator.next (); if (key.equals (pair.key)) { return pair.value; } } return null; } } Actually, put has to update the thing if it already exists. Quiz Monday!