我正在尝试在java中实现一个具有两个键并保持一个集合作为值的Map。请参阅下面的代码。但是,插入方法中似乎有一个错误,我正在努力找到它。如果有人能指出我做错了什么,那就太好了。谢谢
Map<Key1, Map<Key2, Set<Value>>> map;
public PairHashMapSet() {
map = new HashMap<Key1, Map<Key2, Set<Value>>>();
}
public Set<Value> safeGet(final Key1 key1, final Key2 key2) {
if (!map.containsKey(key1) || (!map.get(key1).containsKey(key2))) {
Map<Key2, Set<Value>> map2 = new HashMap<>();
Set<Value> mySet = new HashSet<>();
map2.put(key2, mySet);
map.put(key1, map2);
}
return map.get(key1).get(key2);
}
public void put(Key1 key1, Key2 key2, Value value) {
safeGet(key1, key2).add(value);
}
public Set<Value> get(Key1 key1, Key2 key2) {
return map.get(key1).get(key2);
}
我不能说这是否是唯一的错误,但我首先查看您的"安全获取"方法中的逻辑。
if either
the outer map doesn't have an entry for key1
OR
the outer map has an entry for key1, whose value is a map that doesn't have an entry for key2
then
create an empty set S
create an empty map M2
set (key2 => S) in M2
set (key1 => M2) in the outer map
end if
如果外部映射包含 key1 的条目,仅仅因为旧映射不包含 key2 的条目而替换 key1 引用的映射似乎是否正确?