public class HashTable { private Node[] buckets; private static int BUCKETS; private class Node { int data; Node next; private Node(int item) { data = item; next = null; } } public HashTable(int numBuckets) { BUCKETS = numBuckets; buckets = new Node[BUCKETS]; } public static int hashValue(int item) { if ( item < 0 ) item = -item; return (item % BUCKETS); } public void add(int item) { int h; Node n; h = hashValue(item); n = new Node(item); n.next = buckets[h]; buckets[h] = n; } public boolean contains(int item) { int h; Node p; h = hashValue(item); p = buckets[h]; while ( p != null ) { if ( p.data == item ) return true; p = p.next; } return false; } public boolean remove(int item) { int h; Node cur, back=null; h = hashValue(item); cur = buckets[h]; while ( cur != null ) { if (cur.data == item) { if ( back == null ) buckets[h] = cur.next; else back.next = cur.next; return true; } back = cur; cur = cur.next; } return false; } public void rehash(int numBuckets) { int h; Node [] newtable = new Node[numBuckets]; for (Node p : buckets) { while (p != null) { h = p.data % numBuckets; Node n = new Node(p.data); n.next = newtable[h]; newtable[h] = n; p = p.next; } } buckets = newtable; BUCKETS = numBuckets; } }