// CSE 143, Winter 2010, Marty Stepp // This class implements a set using a "hash table" array. // The hash table stores each integer at a particular given index based // on a "hashing function" represented by the 'bucket' method. // This provides O(1) average time to add, remove, and search. (Wow!) import java.util.*; // for LinkedList public class HashIntSet { private static final int DEFAULT_CAPACITY = 100; // "hash table" - an array of hash "buckets" where values can be stored private List[] elementData; // 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 public HashIntSet(int capacity) { elementData = (LinkedList[]) (new LinkedList[capacity]); } // 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 (elementData[bucket(value)] == null) { elementData[bucket(value)] = new LinkedList(); } if (!contains(value)) { elementData[bucket(value)].add(value); // store 34 at index 4 } } // Returns true if the given value is contained in this set, else false. public boolean contains(int value) { if (elementData[bucket(value)] != null) { return elementData[bucket(value)].contains(value); } else { return false; } } // 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) { if (elementData[bucket(value)] != null) { elementData[bucket(value)].remove(value); } } // helper method to perform a "hashing function" to map the given value to // its appropriate hash table index. private int bucket(int value) { return Math.abs(value) % elementData.length; } }