/** * CSE 373, Winter 2011, Jessica Miller * The StringHashSet is our second implementation of the StringSet interface * (our first implementation was the StreeTreeSet class). This is a hash table * implementation of the Set ADT. */ 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) { // figure out where value should be... int valuePosition = hash(value); // check to see if the value is in the set StringHashEntry temp = table[valuePosition]; while (temp != null) { if (temp.data.equals(value)) { return false; } temp = temp.next; } table[valuePosition] = new StringHashEntry(value, table[valuePosition]); size++; // otherwise, the value was not found and was inserted return true; } /** * Returns true if the set contains the specified String. */ public boolean contains(String value) { // figure out where value should be... int valuePosition = hash(value); // check to see if the value is in the set StringHashEntry temp = table[valuePosition]; 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) { int valuePosition = hash(value); if (table[valuePosition] == null) { // empty bucket return false; } if (table[valuePosition].data.equals(value)) { // removing front table[valuePosition] = table[valuePosition].next; size--; return true; } StringHashEntry temp = table[valuePosition]; while (temp.next != null) { // find value if (temp.next.data.equals(value)) { temp.next = temp.next.next; size--; return true; } temp = temp.next; } return false; } /** * Returns the number of elements in this set (its cardinality) */ public int size() { return size; } 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; } }