Skip to content

Commit

Permalink
Containers in Depth: Exercise 22 - simple implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
kean0212 committed May 17, 2017
1 parent 94ac641 commit 097b0a2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
27 changes: 27 additions & 0 deletions ContainersInDepth/SimpleHashMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.Set;
import java.util.HashSet;
import java.util.ListIterator;
import java.util.Iterator;

public class SimpleHashMap<K, V> extends AbstractMap<K, V> {
static final int SIZE = 997;
Expand Down Expand Up @@ -88,4 +89,30 @@ public void putAll(Map<? extends K, ? extends V> map) {
put((K) mapEntry.getKey(), (V) mapEntry.getValue());
}
}

public void clear() {
for (LinkedList<Map.Entry<K, V>> bucket : buckets) {
if (bucket != null) {
bucket.clear();
}
}
}

@SuppressWarnings("unchecked")
public V remove(Object key) {
V oldValue = null;
int bucketIndex = Math.abs(key.hashCode()) % SIZE;
LinkedList<Map.Entry<K, V>> bucket = buckets[bucketIndex];
if (bucket != null) {
Iterator iterator = bucket.iterator();
while (iterator.hasNext()) {
Map.Entry<K, V> entry = (Map.Entry<K, V>) iterator.next();
if (key != null && key.equals(entry.getKey())) {
oldValue = entry.getValue();
iterator.remove();
}
}
}
return oldValue;
}
}
11 changes: 11 additions & 0 deletions ContainersInDepth/SimpleHashMapDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,16 @@ public static void main(String[] args) {
Util.println("size of collisions: " + simpleHashMap.size());
Util.println("number of collisions: " + simpleHashMap.getNumberOfCollisions()); // size
Util.println("number of probes: " + simpleHashMap.getNumberOfProbes()); // size

simpleHashMap.clear();
Util.println("after clear(): " + simpleHashMap);

simpleHashMap.putAll(capitals);

Util.println("simpleHashMap.remove(\"CAPE VERDE\"): " + simpleHashMap.remove("CAPE VERDE"));
Util.println(simpleHashMap);

Util.println("simpleHashMap.remove(\"hahaha\"): " + simpleHashMap.remove("hahaha"));
Util.println(simpleHashMap);
}
}

0 comments on commit 097b0a2

Please sign in to comment.