// This implementation uses separate // chaining to handle collisions public class HashStringSetV2 { private HashStringNode[] hashTable; private int size; // Constructs a new, empty set with the given underlying capacity public HashStringSetV2(int capacity) { hashTable = new HashStringNode[capacity]; size = 0; } // Given a element, returns the index at which the element should be in private int hashIndex(String element) { int index = Math.abs(element.hashCode() % hashTable.length); return index; } // Returns true if this set contains the specified element and false otherwise public boolean contains(String element) { int index = hashIndex(element); HashStringNode curr = hashTable[index]; // Search the list for the given element while (curr != null) { if (curr.data.equals(element)) { 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(String element) { if (contains(element)) { return false; } // Find the list that the given element should be in int index = hashIndex(element); // Add the element to the front of the list hashTable[index] = new HashStringNode(element, hashTable[index]); 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(String element) { if (!contains(element)) { return false; } // Find the list that the given element is in int index = hashIndex(element); // Remove the given element from that list HashStringNode curr = hashTable[index]; if (curr != null && curr.data.equals(element)) { hashTable[index] = hashTable[index].next; } else { while (curr != null && curr.next != null) { if (curr.next.data.equals(element)) { curr.next = curr.next.next; } curr = curr.next; } } size--; return true; } // Returns the number of elements in this set public int size() { return this.size; } // Returns true if this set contains no elements public boolean isEmpty() { return this.size == 0; } // Node class to store lists in hashTable private static class HashStringNode { public String data; public HashStringNode next; public HashStringNode(String data, HashStringNode next) { this.data = data; this.next = next; } } }