Seperate chaining
Sun Jun 09 2024 10:29:01 GMT+0000 (Coordinated Universal Time)
Saved by
@login
import java.util.LinkedList;
class SeparateChainingHashTable {
private static final int TABLE_SIZE = 10;
LinkedList<String>[] hashTable;
public SeparateChainingHashTable() {
hashTable = new LinkedList[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = new LinkedList<>();
}
}
public int hash(String key) {
return Math.abs(key.hashCode() % TABLE_SIZE);
}
public void insert(String key, String value) {
int index = hash(key);
hashTable[index].add(value);
}
public boolean search(String key, String value) {
int index = hash(key);
return hashTable[index].contains(value);
}
public void display() {
System.out.println("Hash Table Contents:");
for (int i = 0; i < TABLE_SIZE; i++) {
System.out.print("Index " + i + ": ");
if (!hashTable[i].isEmpty()) {
for (String value : hashTable[i]) {
System.out.print(value + " -> ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
SeparateChainingHashTable hashTable = new SeparateChainingHashTable();
// Insert some key-value pairs
hashTable.insert("John", "Doe");
hashTable.insert("Jane", "Smith");
hashTable.insert("Alice", "Johnson");
hashTable.insert("Smith", "Williams");
// Display contents
hashTable.display();
// Search for values
System.out.println("Searching for 'Doe': " + hashTable.search("John", "Doe"));
}
}
content_copyCOPY
Comments