【问题标题】:Java storage and lookup of HashMap in HashSetHashSet中HashMap的Java存储与查找
【发布时间】:2012-08-27 17:35:15
【问题描述】:

我有一个包含多维哈希图的集合,如下所示:

Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>();

我在删除 HashMap 条目时遇到问题。我知道顶级哈希映射的键,但不知道底层哈希映射中的任何数据。我正在尝试通过以下方式删除集合中的哈希映射条目:

我。

Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>();

... Add some hashmaps to the set, then ...

String myKey = "target_key";
setInQuestion.remove(myKey);

二。

Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>();

... Add some hashmaps to the set, then ...

String myKey = "key_one"; //Assume a hashmap has been added with this top level key
HashMap<String, HashMap<String, String>> removeMap = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> dummyMap = new HashMap<String, String>();
removeMap.put(myKey, dummyMap);
setInQuestion.remove(removeMap);

这些方法都不起作用。如果我只知道顶级 hashmap 的键,我将如何删除集合中的条目?

【问题讨论】:

    标签: java hashmap hashset


    【解决方案1】:

    Collection.remove() 要求对象相等。各种 jdk Map 实现实现相等意味着所有键/值必须匹配。由于您传递给 remove() 调用的所有对象都不会与 Set 中的任何地图“相等”,因此不会删除任何内容。

    做你想做的事情的唯一方法是自己遍历 Set 以找到匹配的 Map(或者,将 Set 变成一个以该特殊键为键的 Map)。

    【讨论】:

      【解决方案2】:

      感谢 jtahlborn 的指导。想发布我根据您的回答找到的解决方案:

      String myKey = "Key_In_Question";
      Iterator mySetIterator = myHashSet.iterator();
      while(mySetIterator.hasNext()) {
          HashMap<String, HashMap<String, String>> entry = (HashMap<String, HashMap<String, String>>) mySetIterator.next();
          if(entry.containsKey(myKey)) {
              myHashSet.remove(entry);
          }
      }
      

      【讨论】:

      • 实际上,这将导致 ConcurrentModificationException。请改用mySetIterator.remove()
      【解决方案3】:

      抱歉,我无法将此作为评论发布。我想指出@jtahlborn 关于Map 平等的观点是合同中明确定义的部分......请参阅Map.equals

      ...如果m1.entrySet().equals(m2.entrySet()),则两个映射m1m2 表示相同的映射。这可确保 equals 方法在 Map 接口的不同实现中正常工作。

      Map.Entry.equals 的措辞类似。

      ...e1e2 两个条目表示相同的映射 if

           (e1.getKey()==null ?
             e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &&
            (e1.getValue()==null ?
             e2.getValue()==null : e1.getValue().equals(e2.getValue()))
      

      这可确保equals 方法在Map.Entry 接口的不同实现中正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-18
        • 2013-11-19
        相关资源
        最近更新 更多