// file: MyHashtable.java // author: Robert Keller // purpose: Demonstration of hashing function import java.io.*; import StringList.*; class MyHashtable { int size; // size of StringList table[]; // array of StringLists static int hashPDG(String s) // example of a hashing function { int result = 0; int N = s.length() - 1; int multiplier = 131; while( N >= 0 ) { result = multiplier * result + s.charAt(N); N--; } return result >= 0 ? result : result == Integer.MIN_VALUE ? 0 : Integer.MAX_VALUE + result; } MyHashtable(int size) { this.size = size; table = new StringList[size]; // create array } public static void main(String arg[]) { int size = 10; // size of this hashtable MyHashtable h = new MyHashtable(size); StreamTokenizer input = new StreamTokenizer(System.in); try { while( input.nextToken() != -1 ) { String s = input.sval; int hashValue = hashPDG(s); int index = hashValue % size; System.out.println(s + " --> " + hashValue + " --> " + index); h.table[index] = StringList.cons(s, h.table[index]); } } catch( IOException e ) {} // print the table for( int i = 0; i < size; i++ ) { System.out.print("table[" + i + "] = "); StringList.println(h.table[i], System.out); } } }