// Zorah Fung, CSE 143 // Hash table implementation of a set, an unordered collection without duplicates. // The hash table stores values at indexes determined by a hashing function. // O(1) average time to add, remove, search. // This complete version uses chaining for collision resolution. public class HashSet implements Set { private int size; private HashNode[] elementData; public static final int DEFAULT_CAPACITY = 10; // Builds a new HashSet of the default capacity public HashSet() { this(DEFAULT_CAPACITY); } // Builds a new HashSet of the specified capacity public HashSet(int capacity) { elementData = new HashNode[capacity]; } // Adds the given value to the set // Pre: There is nothing at indexOf(value) @Override public void add(E value) { if (!contains(value)) { int i = indexOf(value); elementData[i] = new HashNode(value, elementData[i]); size++; checkLoad(); } } // Remove the given value from the set @Override public void remove(E value) { if (contains(value)) { int i = indexOf(value); if (elementData[i].data.equals(value)) { elementData[i] = elementData[i].next; } else { HashNode current = elementData[i]; while (!current.next.data.equals(value)) { current = current.next; } current.next = current.next.next; } size--; } } // Checks whether the given value is in the set @Override public boolean contains(E value) { int i = indexOf(value); HashNode current = elementData[i]; while (current != null) { if (current.data.equals(value)) { return true; } current = current.next; } return false; } // Returns the size of the set @Override public int size() { return size; } // Returns true if this set is empty, false otherwise @Override public boolean isEmpty() { return size == 0; } // Uses the hashing function to find the index of a value. private int indexOf(E value) { return Math.abs(value.hashCode() % elementData.length); } // Checks the load and resizes this array if the load exceeds the load factor private void checkLoad() { if ((double) size / elementData.length >= 0.75) { HashNode[] newTable = new HashNode[elementData.length * 2]; for (int i = 0; i < elementData.length; i++) { while (elementData[i] != null) { Object value = elementData[i].data; int newIndex = Math.abs(value.hashCode() % newTable.length); newTable[newIndex] = new HashNode(value, newTable[newIndex]); // add to the new table elementData[i] = elementData[i].next; // remove the value from the old table } } elementData = newTable; } } }