這裏是一個只讀地圖(未經測試!),這是備份用任何數量的其他地圖:
private class ReadonlyProxyMap<K, V> implements Map<K, V> {
private final List<Map<K, V>> maps = new ArrayList<>();
public void addMap(Map<K, V> map) {
maps.add(map);
}
@Override
public int size() {
return entrySet().size();
}
@Override
public boolean isEmpty() {
for (Map<K, V> map : maps) {
if (!map.isEmpty()) {
return false;
}
}
return true;
}
@Override
public boolean containsKey(Object key) {
for (Map<K, V> map : maps) {
if (map.containsKey(key)) {
return true;
}
}
return false;
}
@Override
public boolean containsValue(Object value) {
for (Map<K, V> map : maps) {
if (map.containsValue(value)) {
return true;
}
}
return false;
}
@Override
public V get(Object key) {
for (Map<K, V> map : maps) {
if (map.containsKey(key)) {
return map.get(key);
}
}
return null;
}
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void clear() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Set<K> keySet() {
Set<K> keySet = new HashSet<>();
for (Map<K, V> map : maps) {
keySet.addAll(map.keySet());
}
return keySet;
}
@Override
public Collection<V> values() {
List<V> values = new ArrayList<>();
for (Map.Entry<K, V> entry : entrySet()) {
values.add(entry.getValue());
}
return values;
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
Set<K> keySet = new HashSet<>();
Set<Map.Entry<K, V>> entrySet = new HashSet<>();
for (Map<K, V> map : maps) {
for (Map.Entry<K, V> entry : map.entrySet()) {
if (!keySet.contains(entry.getKey())) {
entrySet.add(entry);
keySet.add(entry.getKey());
}
}
}
return entrySet;
}
}
然後你可以使用:
Map<Id, Person> usersById = new HashMap<>();
Map<Id, Person> managersById = new HashMap<>();
ReadonlyProxyMap<Id, Person> allPersons = new ReadonlyProxyMap<>();
...
allPersons.addMap(usersById);
allPersons.addMap(managersById);
...
Person findArbitraryPerson(Id id) {
return allPersons.get(myId);
}
你是什麼意思「,但我必須在每次到達時向該地圖添加一個新的Person實例,並將其刪除等。「這裏有什麼意圖? – Sikorski
爲什麼你首先有兩個hashmaps? –
爲什麼你不能只使用用戶的地圖?經理沒有「用戶」ID? – Alessio