// "Quick and dirty" implementation of HashSet that still // roughly matches Java's in efficiency. public class HashSet { private static final int DEFAULT_CAPACITY = 1000; private HashNode[] table; private int size; public HashSet() { this(DEFAULT_CAPACITY); } public HashSet(int capacity) { // default load factor is 0.5 table = new HashNode[(int)(capacity / 0.5)]; size = 0; } public void add(E element) { if (!contains(element)) { int index = indexOf(element); table[index] = new HashNode(element, table[index]); size++; } } public boolean contains(E element) { int index = indexOf(element); HashNode curr = table[index]; while (curr != null) { if (curr.value.equals(element)) { return true; } curr = curr.next; } return false; } public void remove(E element) { if (contains(element)) { int index = indexOf(element); if (table[index].value.equals(element)) { table[index] = table[index].next; } else { HashNode curr = table[index]; while (curr.next != null && !curr.next.value.equals(element)) { curr = curr.next; } curr.next = curr.next.next; } size--; } } public int size() { return size; } private int indexOf(E element) { return Math.abs(element.hashCode() % table.length); } private static class HashNode { public Object value; public HashNode next; public HashNode(Object value) { this(value, null); } public HashNode(Object value, HashNode next) { this.value = value; this.next = next; } } }