To add the functionality of deleting key-value pairs from the hash table, we can implement a method called delete
. This method takes a key as input and removes the entry with the matching key from the hash table.
Here's an example implementation of the delete
method in Java:
TEXT/X-JAVA
1<CODE>
xxxxxxxxxx
56
}
class HashTable {
private final int INITIAL_SIZE = 16;
private HashEntry[] entries;
public HashTable() {
entries = new HashEntry[INITIAL_SIZE];
}
// Method to delete key-value pairs from the hash table
public void delete(String key) {
int index = getIndex(key);
// Check if the index is empty
if (entries[index] == null) {
return;
}
// Check if the first entry matches the key
if (entries[index].key.equals(key)) {
entries[index] = entries[index].next;
return;
}
// Traverse the chain of entries at the index
HashEntry current = entries[index];
HashEntry previous = null;
while (current != null) {
// Check if the current entry matches the key
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment