【发布时间】:2013-10-18 05:09:53
【问题描述】:
所以,我有两个 hashMaps
public HashMap<String, Integer> map1 = new HashMap<String,Integer>();
public HashMap<String, Integer> map2 = new HashMap<String,Integer>();
我想创建一个哈希图,它由这两个哈希图合并而成。
另外,当我向这两个哈希图中的任何一个添加元素时:
map1.put("key",1);
第三个 hashmap 应该有这个变化
解决方案:
import java.util.*;
public final class JoinedMap {
static class JoinedMapView<K,V> implements Map<K,V> {
private final Map<? extends K,? extends V>[] items;
public JoinedMapView(final Map<? extends K,? extends V>[] items) {
this.items = items;
}
@Override
public int size() {
int ct = 0;
for (final Map<? extends K,? extends V> map : items) {
ct += map.size();
}
return ct;
}
@Override
public boolean isEmpty() {
for (final Map<? extends K,? extends V> map : items) {
if(map.isEmpty()) return true;
}
return false;
}
@Override
public boolean containsKey(Object key) {
for (final Map<? extends K,? extends V> map : items) {
if(map.containsKey(key)) return true;
}
return false;
}
@Override
public boolean containsValue(Object value) {
for (final Map<? extends K,? extends V> map : items) {
if(map.containsValue(value)) return true;
}
return false;
}
@Override
public V get(Object key) {
for (final Map<? extends K,? extends V> map : items) {
if(map.containsKey(key)){
return map.get(key);
}
}
return null;
}
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
for (final Map<? extends K,? extends V> map : items) {
map.clear();
}
}
@Override
public Set<K> keySet() {
Set<K> mrgSet = new HashSet<K>();
for (final Map<? extends K,? extends V> map : items) {
mrgSet.addAll(map.keySet());
}
return mrgSet;
}
@Override
public Collection<V> values() {
Collection<V> values = new ArrayList<>();
for (final Map<? extends K,? extends V> map : items) {
values.addAll(map.values());
}
return values;
}
@Override
public Set<Entry<K, V>> entrySet() {
throw new UnsupportedOperationException();
}
}
/**
* Returns a live aggregated map view of the maps passed in.
* None of the above methods is thread safe (nor would there be an easy way
* of making them).
*/
public static <K,V> Map<K,V> combine(
final Map<? extends K, ? extends V>... items) {
return new JoinedMapView<K,V>(items);
}
private JoinedMap() {
}
}
【问题讨论】:
-
@andras 这不是完全相同的副本。这里的问题是不同的。在将其作为重复项关闭之前,请仔细阅读该问题。
-
我希望第三张地图能够对前两张地图进行任何更改。这样不行
-
如果 map1 和 map2 都有 keyX 会怎样?当您执行 mergeMap.put(KeyNooneElseHas) 时会发生什么?
-
你能解释一下你想达到什么目标吗?也许有更好的方法?
-
@mlk 提出了一些有趣的问题。您可能想要的是提供两个地图的“视图”,而不是在任一地图发生任何事情时必须维护的其他地图。 Guava
Iterators.concat可能是朝着正确方向迈出的一步......