import java.util.*; import java.lang.Math; public class HashTable { public static int myHash(String key) { int hashValue = (Math.abs(key.hashCode())) % 5; return hashValue; } public static void insert(LinkedList[] hashTable, String s) { int h = myHash(s); if (hashTable[h] == null) hashTable[h] = new LinkedList(); hashTable[h].add(s); // adds s to the list at the right position in hash table } public static boolean search(LinkedList[] hashTable, String s) { int h = myHash(s); // look in position h in the hash table for s: if (hashTable[h] != null) { ListIterator li = hashTable[h].listIterator(0); while (li.hasNext()) { String nextString = (String) li.next(); if (s.equals(nextString)) return true; } } return false; } public static void delete(LinkedList[] hashTable, String s) { int h = myHash(s); // look in position h in the hash table for s: if (hashTable[ h] != null) { hashTable[h].remove(s); } } public static void main(String[] args) { LinkedList[] hashTable = new LinkedList[5]; insert(hashTable, "Dog"); insert(hashTable, "Cat"); insert(hashTable, "CS 223"); insert(hashTable, "Brendan"); insert(hashTable, "Car"); insert(hashTable, "Lunch"); for (int i = 0; i < 10; i++) { String newString = "Test string " + i; insert(hashTable, newString); } System.out.println("Before:"); for (int i = 0; i < hashTable.length; i++) System.out.println("hashTable[" + i + "] = " + hashTable[i]); delete(hashTable, "Brendan"); delete(hashTable, "Test string 7"); delete(hashTable, "Blah"); System.out.println("After:"); for (int i = 0; i < hashTable.length; i++) System.out.println("hashTable[" + i + "] = " + hashTable[i]); } }