/* * Kyle Pierce * CSE 143 * * This is a quick and dirty HashSet implementation */ public class HashSet { public int size; public HashNode[] table; /* * Constructs a new HashSet using the given size */ public HashSet(int length) { table = (HashNode[]) new HashNode[length]; size = 0; } /* * Adds the given element to this HashSet * Returns true if the addition was successful */ public void add(E e) { if (!contains(e)) { int i = hash(e); table[i] = new HashNode(e, table[i]); size++; } } /* * Returns true if the given element is contained in this HashSet * and false otherwise */ public boolean contains(E e) { int i = hash(e); HashNode current = table[i]; while (current != null) { if (current.data.equals(e)) { return true; } current = current.next; } return false; } /* * Removes the given element from this HashSet * Returns true if the removal was successful */ public void remove(E e) { if (contains(e)) { int i = hash(e); if (table[i].data.equals(e)) { table[i] = table[i].next; } else { HashNode current = table[i]; while (!current.next.data.equals(e)) { current = current.next; } current.next = current.next.next; } size--; } } /* * Returns the size of this HashSet */ public int size() { return size; } /* * Returns the hash of the given element */ private int hash(E e) { return Math.abs(e.hashCode()) % table.length; } }