// 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. // This very basic implementation has no collision resolution so it will only work // if all inserted values hash to unique indexes. public class HashSetIncomplete implements Set { private int size; private E[] elementData; public static final int DEFAULT_CAPACITY = 10; // Builds a new HashSet of the default capacity public HashSetIncomplete() { this(DEFAULT_CAPACITY); } // Builds a new HashSet of the specified capacity public HashSetIncomplete(int capacity) { elementData = (E[]) new Object[capacity]; // don't worry about this casting } // Adds the given value to the set // Pre: There is nothing at indexOf(value) public void add(E value) { if (!contains(value)) { elementData[indexOf(value)] = value; size++; } } // Remove the given value from the set public void remove(E value) { if (contains(value)) { elementData[indexOf(value)] = null; size--; } } // Checks whether the given value is in the set public boolean contains(E value) { return elementData[indexOf(value)] != null; } // Returns the size of the set public int size() { return size; } // Returns true if this set is empty, false otherwise public boolean isEmpty() { return size == 0; } // Returns the String representation of this set. public String toString() { if (isEmpty()) { return "[]"; } else { String result = "["; for (int i = 0; i < elementData.length; i++) { if (elementData[i] != null) { result += elementData[i] + ", "; } } return result.substring(0, result.length() - 2) + "]"; } } // Uses the hashing function to find the index of a value. private int indexOf(E value) { return Math.abs(value.hashCode() % elementData.length); } }