-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSlowMap.java
More file actions
50 lines (43 loc) · 1.29 KB
/
SlowMap.java
File metadata and controls
50 lines (43 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package thinkinginjava.containers;
// A Map implemented with ArrayLists.
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import thinkinginjava.util.Countries;
public class SlowMap<K, V> extends AbstractMap<K, V> {
private List<K> keys = new ArrayList<K>();
private List<V> values = new ArrayList<V>();
public V put(K key, V value) {
V oldValue = get(key); // The old value or null
if (!keys.contains(key)) {
keys.add(key);
values.add(value);
} else
values.set(keys.indexOf(key), value);
return oldValue;
}
public V get(Object key) { // key is type Object, not K
if (!keys.contains(key))
return null;
return values.get(keys.indexOf(key));
}
public Set<Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> set = new HashSet<Map.Entry<K, V>>();
Iterator<K> ki = keys.iterator();
Iterator<V> vi = values.iterator();
while (ki.hasNext())
set.add(new MapEntry<K, V>(ki.next(), vi.next()));
return set;
}
public static void main(String[] args) {
SlowMap<String, String> m = new SlowMap<String, String>();
m.putAll(Countries.capitals(15));
System.out.println(m);
System.out.println(m.get("BULGARIA"));
System.out.println(m.entrySet());
}
}