Hashing Most of this lecture is covered in CLR Ch. 12 except the Java Hashtable idiom below. I discussed the material in 12.1, 12.2, 12.4. Important concepts: collision, load factor, simple uniform hashing condition, statement of Thm 12.1 and 12.2 p. 224-5, open address hashing for collision resolution, linear probing, quadratic probing, double hashing. --------------------------------------------------------------- Java Hashtable idiom The following example represents a common Java idiom involving Hashtables. This is typical code that you might find in a compiler for handling symbol tables for example. The class Hashtable is defined in java.util. In Java, a Hashtable is a mapping from Objects to Objects. Any Object can be used as a key and any Object can be used as the data. In this example the data objects are Orcs and the key is a String, which is interpreted as the name of the Orc. The constructor of Orc enters the new Orc in the hashtable. It assumes that no Orc with the given name already exists in the hashtable. The static method lookup(name) checks whether an Orc with the given name already exists in the table; if so, it returns it, and if not, it creates a new Orc with that name and returns it. import java.util.*; class Orc { String name; int strength; static final int defaultStrength = 10; private static Hashtable orcHash = new Hashtable(); Orc(String n, int s) { name = n; strength = s; orcHash.put(name,this); } Orc(String n) { this(n,defaultStrength); } static Orc lookup(String name) { return orcHash.containsKey(name)?(Orc)orcHash.get(name):new Orc(name); } } An alternative implementation of lookup is static Orc lookup(String name) { Orc o = (Orc)orcHash.get(name); if (o == null) return new Orc(name); else return o; } A couple things to note: (i) the Hashtable orcHash is a *static* object associated with the class Orc. This means there is only one of them for the whole class. It is private, which means it is invisible outside the class--the only methods that should ever need to access it are the constructor and lookup. (ii) to check for existence of a key in the table, use containsKey(Object), not contains(Object). Beware: the latter function exists, but it does something different. It checks whether the given Object exists in the table as data, not as a key. (iii) the constructor assumes that no Orc with the given name already exists in the table. If it does, the old Orc with that name will just be replaced by the new one. (iv) in lookup(), the call orcHash.get(name) returns an Object, which must be cast down to type Orc using the typecast operator (Orc) before returning.