// Jeremy Lipschutz // A class representing a set of elements public class MyHashSet { private static final int DEFAULT_CAPACITY = 10; private HashSetNode[] table; private int size; // Constructs a new, empty set with the given underlying capacity public MyHashSet(int capacity) { table = new HashSetNode[capacity]; size = 0; } // Constructs a new, empty set with the default capacity public MyHashSet() { this(DEFAULT_CAPACITY); } // Returns true if this set contains the specified element and false otherwise public boolean contains(E str) { int index = hashIndex(str); HashSetNode curr = table[index]; while (curr != null) { if (curr.data.equals(str)) { return true; } curr = curr.next; } return false; } // Adds the specified element to this set if it is not already present. // Returns true if the element was not already present and false otherwise public boolean add(E str) { if (contains(str)) { return false; } int index = hashIndex(str); HashSetNode curr = table[index]; HashSetNode newNode = new HashSetNode(str, curr); table[index] = newNode; size++; return true; } // Removes the specified element from this set if it is present. // Returns true if the element was present and false otherwise public boolean remove(E str) { if (!contains(str)) { return false; } int index = hashIndex(str); HashSetNode curr = table[index]; if (curr.data.equals(str)) { table[index] = table[index].next; } else { while (!curr.next.data.equals(str)) { curr = curr.next; } curr.next = curr.next.next; } size--; return true; } // Returns the number of elements in this set public int size() { return size; } // Returns true if this set contains no elements public boolean isEmpty() { return size == 0; } // Given a element, returns the index at which the element should be in private int hashIndex(E str) { return Math.abs(str.hashCode() % table.length); } // Node class to store the given element and a reference // to the next node in the linked list private static class HashSetNode { public E data; public HashSetNode next; // Constructor that sets its data to the given data, and takes a reference // for the next node in the linked list public HashSetNode(E data, HashSetNode next) { this.data = data; this.next = next; } // Constructor that sets its deta to the given data // and null link public HashSetNode(E data) { this(data, null); } } }