Skip to content

Commit 73ddcf1

Browse files
author
jsquared21
committed
Edit method MyHashMap.remove(key) for efficiency
1 parent 5711790 commit 73ddcf1

File tree

2 files changed

+9
-9
lines changed

2 files changed

+9
-9
lines changed
-27 Bytes
Binary file not shown.

Exercise_27/Exercise_27_04/MyHashMap.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public java.util.Set<V> getAll(K key) {
110110
if (table.get(index).getKey().equals(key)) {
111111
set.add(table.get(index).getValue());
112112
}
113-
113+
114114
index++;
115115
index %= capacity;
116116
}
@@ -162,18 +162,18 @@ public V put(K key, V value) {
162162
@Override /** Remove the entry for the specified key */
163163
public void remove(K key) {
164164
int index = hash(key.hashCode());
165-
int i = index - 1;
166165

167-
while (i != index && (table.get(index) == null ||
168-
table.get(index).getKey() != key)) {
166+
// Remove the first entry that matches the key
167+
while (table.get(index) != null) {
168+
if (table.get(index).getKey().equals(key)) {
169+
table.remove(index);
170+
size--; // Decrease size
171+
break; // Remove just one entry that matches the key
172+
}
173+
169174
index++;
170175
index %= capacity;
171176
}
172-
173-
if (table.get(index).getKey() == key) {
174-
table.remove(index);
175-
size--; // Decrease size
176-
}
177177
}
178178

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

0 commit comments

Comments
 (0)