Skip to content

Commit a2e5a72

Browse files
author
jsquared21
committed
Edit method MyHashMap.remove(key) for efficiency
1 parent 103dd52 commit a2e5a72

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed
-32 Bytes
Binary file not shown.

Exercise_27/Exercise_27_02/MyHashMap.java

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -159,19 +159,17 @@ public V put(K key, V value) {
159159
@Override /** Remove the entry for the specified key */
160160
public void remove(K key) {
161161
int index = hash(key.hashCode());
162-
int i = index - 1; // One cycle of the arraylist
163162
int j = 0;
164-
165-
while ((table.get(index) == null ||
166-
table.get(index).getKey() != key) && i != index) {
163+
164+
while (table.get(index) != null) {
165+
if (table.get(index).getKey() == key) {
166+
table.remove(index);
167+
size--; // Decrease size
168+
break; // Remove just one entry that matches key
169+
}
167170
index += Math.pow(j++, 2);
168171
index %= capacity;
169172
}
170-
171-
if (table.get(index).getKey() == key) {
172-
table.remove(index);
173-
size--; // Decrease size
174-
}
175173
}
176174

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

0 commit comments

Comments
 (0)