为何无法在自制哈希表的链表数组中添加新条目?
Hey there, let's break down why your hash table is only keeping the last entry you add, and how to fix it!
The Root Cause
Looking at your put method, you removed the check for whether myTable[index] is already initialized:
public void put(String key, Integer value) { int index = hash(key); //if(myTable[index] == null) { myTable[index] = new LinkedList<Entry>(); // This line is the problem! Entry entry = new Entry(key, value); myTable[index].add(entry); //} }
Every time you call put, you're creating a new empty LinkedList at the calculated index, which overwrites any existing list that was there. That's why only your last entry ("amazing") remains—each subsequent put wipes out the previous entries at that index.
The Fix
You need to only create a new LinkedList if the index doesn't already have one. Also, it's a good practice to check if the key already exists in the list and update its value instead of adding a duplicate entry. Here's the corrected put method:
public void put(String key, Integer value) { int index = hash(key); // Initialize the list only if it's null if (myTable[index] == null) { myTable[index] = new LinkedList<Entry>(); } // Check if the key already exists to update the value for (Entry existingEntry : myTable[index]) { if (existingEntry.getKey().equals(key)) { existingEntry.setValue(value); // Make sure your Entry class has this method! return; } } // If key doesn't exist, add a new entry Entry entry = new Entry(key, value); myTable[index].add(entry); }
Don't forget to add a setValue method to your Entry class (since you already have getKey and getValue):
class Entry { private String key; private Integer value; public Entry(String key, Integer value) { this.key = key; this.value = value; } public String getKey() { return key; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } }
What Happens After the Fix?
When you run your main method again:
public static void main(String[] args) { HashTable hashTable = new HashTable(10); hashTable.put("something", 20); hashTable.put("new", 21); hashTable.put("amazing", 100); System.out.println(hashTable.containsKey("something")); }
It will output true instead of false, because all entries are now stored in their respective index lists without being overwritten.
Extra Improvements
- Your
hashmethod can return negative values (sincehashCode()can be negative), so adjust it to ensure non-negative indexes:public int hash(String item) { int hash = item.hashCode(); return Math.abs(hash) % this.getCapacity(); } - Add null checks in
containsKeyandgetto avoidNullPointerExceptionwhen an index has no entries:public boolean containsKey(String key) { int index = hash(key); if (myTable[index] == null) { return false; } // Rest of your code... }
内容的提问来源于stack exchange,提问作者Manhar

