// Quick and dirty implementation of HashSet. handout #36 public class HashSet<E> { private HashNode[] data; private int size; public HashSet(int capacity) { // initialize array with load factor of 0.75 data = new HashNode[(int) (capacity / 0.75)]; } public void add(E value) { if (!contains(value)) { int i = indexOf(value); data[i] = new HashNode(value, data[i]); size++; } } public boolean contains(E value) { int i = indexOf(value); HashNode current = data[i]; while (current != null) { if (current.data.equals(value)) return true; current = current.next; } return false; } public void remove(E value) { if (contains(value)) { int i = indexOf(value); if (data[i].data.equals(value)) data[i] = data[i].next; else { HashNode current = data[i]; while (!current.next.data.equals(value)) current = current.next; current.next = current.next.next; } size--; } } public int size() { return size; } private int indexOf(E value) { return Math.abs(value.hashCode() % data.length); } private static class HashNode { public Object data; public HashNode next; public HashNode(Object data, HashNode next) { this.data = data; this.next = next; } } }
Stuart Reges
Last modified: Wed Jun 4 16:18:07 PDT 2008