/** * CSE 373, Spring 2011, Jessica Miller * A set for Strings backed by a hash table. The hash table is using separate * chaining as its collision resolution strategy. */ public class StringHashSet implements StringSet { private static final int DEFAULT_SIZE = 11; private StringHashEntry[] table; private int size; public StringHashSet() { this(DEFAULT_SIZE); } public StringHashSet(int tableSize) { table = new StringHashEntry[tableSize]; size = 0; } /** * Adds the specified String to the Set if it is not already present. * @return true if this set did not already contain the String */ public boolean add(String value) { // does the set already contain the value? if (contains(value)) { return false; } // figure out where value should go... int bucket = hash(value); // insert the new value StringHashEntry newEntry = new StringHashEntry(value, table[bucket]); table[bucket] = newEntry; size++; return true; } /** * Returns true if the set contains the specified String. */ public boolean contains(String value) { // figure out where value should be... int bucket = hash(value); // check to see if the value is in the set StringHashEntry temp = table[bucket]; while (temp != null) { if (temp.data.equals(value)) { return true; } temp = temp.next; } // otherwise, the value was not found return false; } /** * Prints the set in a hash table-like format. */ public void print() { for (int i = 0; i < table.length; i++) { System.out.printf("%d: ", i); StringHashEntry temp = table[i]; while (temp != null) { System.out.print(temp.data); if (temp.next != null) { System.out.print(" --> "); } temp = temp.next; } System.out.println(); } } /** * Removes the specified String from this set if it is present. * @return true if this set contained the specified element */ public boolean remove(String value) { return false; } /** * Returns the number of elements in this set (its cardinality) */ public int size() { return size; } /** * Calculating a String's hash value via polynomial accumulation and * Horner's rule. * @param data * @return */ private int hash(String data) { int hashVal = 0; for (int i = 0; i < data.length(); i++) { hashVal = 37 * hashVal + data.charAt(i); } hashVal %= table.length; if (hashVal < 0) { hashVal += table.length; } return hashVal; } }