forked from googlemaps/android-maps-utils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BiMultiMap.java
83 lines (72 loc) · 2.53 KB
/
BiMultiMap.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.google.maps.android.geojson;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Extension of HashMap that provides two main features. Firstly it allows reverse lookup
* for a key given a value, by storing a second HashMap internally which maps values to keys.
* Secondly, it supports Collection values, in which case, each item in the collection is
* used as a key in the internal reverse HashMap. It's therefore up to the caller to ensure
* the overall set of values, and collection values, are unique.
*
* Used by GeoJsonRenderer to store GeoJsonFeature instances mapped to corresponding Marker,
* Polyline, and Polygon map objects. We want to look these up in reverse to provide access
* to GeoJsonFeature instances when map objects are clicked.
*/
/* package */ class BiMultiMap<K> extends HashMap<K, Object> {
private final Map<Object, K> mValuesToKeys = new HashMap<>();
@Override
public void putAll(Map<? extends K, ?> map) {
// put() manages the reverse map, so call it on each entry.
for (Entry<? extends K, ?> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public Object put(K key, Object value) {
// Store value/key in the reverse map.
mValuesToKeys.put(value, key);
return super.put(key, value);
}
public Object put(K key, Collection values) {
// Store values/key in the reverse map.
for (Object value : values) {
mValuesToKeys.put(value, key);
}
return super.put(key, values);
}
@Override
public Object remove(Object key) {
Object value = super.remove(key);
// Also remove the value(s) and key from the reverse map.
if (value instanceof Collection) {
for (Object valueItem : (Collection) value) {
mValuesToKeys.remove(valueItem);
}
} else {
mValuesToKeys.remove(value);
}
return value;
}
@Override
public void clear() {
super.clear();
mValuesToKeys.clear();
}
@SuppressWarnings("unchecked")
@Override
public BiMultiMap<K> clone() {
BiMultiMap<K> cloned = new BiMultiMap<>();
cloned.putAll((Map<K, Object>) super.clone());
return cloned;
}
/**
* Reverse lookup of key by value.
*
* @param value Value to lookup
* @return Key for the given value
*/
public K getKey(Object value) {
return mValuesToKeys.get(value);
}
}