// CSE 143, Winter 2009, Marty Stepp // A HashIntSet implements a set of integers using a hash table. // This provides O(1) average time to add, remove, and search. (Wow!) import java.util.LinkedList; import java.util.List; public class HashIntSet { private static final int DEFAULT_CAPACITY = 131377; // some arbitrary large number // "hash table" - an array of hash "buckets" where values can be stored private List[] hashTable; // Creates a new empty set with a hash table of default capacity. public HashIntSet() { this(DEFAULT_CAPACITY); } // Creates a new empty set with the given capacity. // Precondition: capacity > 0 // The @SuppressWarnings("unchecked") below is to avoid a compiler warning // for casting to a generic type. @SuppressWarnings("unchecked") public HashIntSet(int capacity) { hashTable = (List[]) (new List[capacity]); for (int i = 0; i < hashTable.length; i++) { hashTable[i] = new LinkedList(); } } // Adds the given value to this set. If it is already contained in // this set, no change is made, because sets do not allow duplicates. public void add(int value) { if (!contains(value)) { int index = value % hashTable.length; hashTable[index].add(value); } } // Returns true if the given value is contained in this set. public boolean contains(int value) { int index = value % hashTable.length; return hashTable[index].contains(value); } // Removes the given value from this set if it is contained in the set. // If the value is not contained in the set, no change is made. public void remove(int value) { int index = value % hashTable.length; hashTable[index].remove((Integer) value); } }