/* Word.java */ /** Implements a Word, which is a Hashable String. * Words are automatically stored in lowercase. */ import Supporting.*; public class Word implements Hashable { /** Constructs a new word. * @param v in lower case will be the string value of the word. */ public Word( String v ) { key = v.toLowerCase(); } /** Returns the String value of this word. * @returns a String value of this word. */ public String toString() { return key; } /** Get the length. * @return the length of the word. */ public int length() { return key.length(); } /** Returns the hashed value of this String as an integer. * Hashed value in the range: [0 ... tableSize-1] */ public int hash( int tableSize ) { // NOTE : This is a terrible hash function. if( key.length() == 0 ) return 0; int c = key.charAt(0) - 'a'; if( c < 0 ) { c = -c; } return c; } /** An alternate hash function (the String hash function in Java). */ public int hash1( int tableSize ) { int hashVal = key.hashCode(); if (hashVal < 0) { hashVal = -hashVal; } return hashVal % tableSize; } /** An alternate hash function (from lecture). */ public int hash2( int tableSize ) { int hashVal = 0; for (int i = 0; i < key.length(); i++) { hashVal = (128 * hashVal + key.charAt(i)) % tableSize; } return hashVal; } /** Determines whether two words are equal. * @returns returns true <==> string values of things and o are equal. * @exception ClassCastException if o is not a Word. */ public boolean equals( Object o ) { Word wo = (Word)o; return key.equals(wo.key); } private String key; }