2017-01-10 14:11:16 -08:00
|
|
|
// equalshashcode/SlowMap.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// A Map implemented with ArrayLists
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
2015-11-11 20:20:04 -08:00
|
|
|
import onjava.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2015-09-07 11:44:36 -06:00
|
|
|
public class SlowMap<K, V> extends AbstractMap<K, V> {
|
2015-06-15 17:47:35 -07:00
|
|
|
private List<K> keys = new ArrayList<>();
|
|
|
|
private List<V> values = new ArrayList<>();
|
|
|
|
@Override
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public V get(Object key) { // key is type Object, not K
|
|
|
|
if(!keys.contains(key))
|
|
|
|
return null;
|
|
|
|
return values.get(keys.indexOf(key));
|
|
|
|
}
|
|
|
|
@Override
|
2015-09-07 11:44:36 -06:00
|
|
|
public Set<Map.Entry<K, V>> entrySet() {
|
|
|
|
Set<Map.Entry<K, V>> set= new HashSet<>();
|
2015-06-15 17:47:35 -07:00
|
|
|
Iterator<K> ki = keys.iterator();
|
|
|
|
Iterator<V> vi = values.iterator();
|
|
|
|
while(ki.hasNext())
|
|
|
|
set.add(new MapEntry<>(ki.next(), vi.next()));
|
|
|
|
return set;
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
SlowMap<String,String> m= new SlowMap<>();
|
2017-01-10 14:11:16 -08:00
|
|
|
m.putAll(Countries.capitals(8));
|
|
|
|
m.forEach((k, v) ->
|
|
|
|
System.out.println(k + "=" + v));
|
|
|
|
System.out.println(m.get("BENIN"));
|
|
|
|
m.entrySet().forEach(System.out::println);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2017-01-10 14:11:16 -08:00
|
|
|
CAMEROON=Yaounde
|
|
|
|
ANGOLA=Luanda
|
|
|
|
BURKINA FASO=Ouagadougou
|
|
|
|
BURUNDI=Bujumbura
|
|
|
|
ALGERIA=Algiers
|
|
|
|
BENIN=Porto-Novo
|
|
|
|
CAPE VERDE=Praia
|
|
|
|
BOTSWANA=Gaberone
|
|
|
|
Porto-Novo
|
|
|
|
CAMEROON=Yaounde
|
|
|
|
ANGOLA=Luanda
|
|
|
|
BURKINA FASO=Ouagadougou
|
|
|
|
BURUNDI=Bujumbura
|
|
|
|
ALGERIA=Algiers
|
|
|
|
BENIN=Porto-Novo
|
|
|
|
CAPE VERDE=Praia
|
|
|
|
BOTSWANA=Gaberone
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|