数据结构

时间:2018-01-30 16:45:16

标签: java dictionary

我试图在java中实现一个有两个键的Map并将一个set维护为一个值。请看下面的代码。但是,插入方法似乎存在一个错误,我很难找到它。如果有人可以指出我做错了什么就会很棒。感谢

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);
}

1 个答案:

答案 0 :(得分:0)

我不能说这是否只是 错误,但我首先要查看“安全获取”方法中的逻辑。

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的条目,是否正确替换key1引用的地图,因为旧地图不包含key2的条目?

相关问题