Skip to content

Commit 5c40747

Browse files
author
jsquared21
committed
Edit method MyHashMap.remove(key) for efficiency
1 parent c73855d commit 5c40747

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed
10 Bytes
Binary file not shown.

Exercise_27/Exercise_27_03/MyHashMap.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -166,16 +166,18 @@ public void remove(K key) {
166166
int index = hash1;
167167
int j = 0;
168168

169-
while (table.get(index) == null) {
169+
// Remove the first entry that matched the key
170+
while (table.get(index) != null) {
171+
if (table.get(index).getKey().equals(key)) {
172+
table.remove(index);
173+
size--; // Decrease size
174+
break; // Remove just one entry that matches the key
175+
}
176+
170177
// Secondary hash: (k + j * h'(key)) % N
171178
index = hash1 + j++ * hash2(hash1);
172179
index %= capacity;
173180
}
174-
175-
if (table.get(index).getKey() == key) {
176-
table.remove(index);
177-
size--; // Decrease size
178-
}
179181
}
180182

181183
@Override /** Return the number of entries in this map */

0 commit comments

Comments
 (0)