// Erika Wolfe, 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; // Constructs an empty set of default capacity public HashSetIncomplete() { size = 0; // this is how you make generic arrays elementData = (E[]) new Object[DEFAULT_CAPACITY]; } // Adds the given value to the set public void add(E val) { if (!contains(val)) { int index = indexOf(val); elementData[index] = val; size++; } } // Returns the size of this set public int size() { return size; } // Returns true if the set has no elements, false otherwise. public boolean isEmpty() { return size == 0; } // Returns whether the given value is in the set public boolean contains(E val) { int index = indexOf(val); return elementData[index] != null; } // Removes the given value from the set // If the set does not contain the given value, the set is unmodified. public void remove(E val) { if (contains(val)) { int index = indexOf(val); elementData[index] = null; size--; } } // Uses the hashing function to find the index of a value. private int indexOf(E val) { return Math.abs(val.hashCode()) % elementData.length; } }