【问题标题】:HashMap in a HashMapHashMap 中的 HashMap
【发布时间】:2012-05-28 21:47:16
【问题描述】:

更新:-

问题陈述是-

我需要储存这些东西-

For ID corresponding to 1, I need to Store these things

 - Key CGUID(String CGUID) and its Value, Key SGUID(String SGUID) and its Value, Key PGUID(String PGUID) and its Value, Key UID(String UID) and its Value, Key ALOC(String ALOC) and its Value

For ID corresponding to 2, I need to Store these things

- Key CGUID(String CGUID) and its Value, Key SGUID(String SGUID) and its Value, Key PGUID(String PGUID) and its Value, Key UID(String UID) and its Value, Key ALOC(String ALOC) and its Value

For ID corresponding to 3, I need to Store these things

- Key CGUID(String CGUID) and its Value, Key SGUID(String SGUID) and its Value, Key PGUID(String PGUID) and its Value, Key UID(String UID) and its Value, Key ALOC(String ALOC) and its Value

所以对于这个问题,我正在考虑制作这样的数据结构-

public static LinkedHashMap<String, Integer> GUID_VALUES = new LinkedHashMap<String, Integer>();

public static LinkedHashMap<Integer, LinkedHashMap<String, Integer>> GUID_ID_MAPPING = new LinkedHashMap<Integer, LinkedHashMap<String, Integer>>();

还有比这更好的方法吗?

【问题讨论】:

  • 泛型用于类型,而不是值。
  • 听起来像是一棵支持基于路径的查询的树,比如 XPath。
  • 是 CGUID 键和值,与 ID 1 和 ID 2 相关,换句话说,它将是相同的映射或结构(这也适用于其他键/值对)?
  • 通过 CGUID 键我的意思是字符串 CGUID,我用更多信息更新了问题。
  • 再看评论,我已经编辑好了。

标签: java hashmap linkedhashmap


【解决方案1】:

您最终要存储什么并不完全清楚。

如果你只是想要一张地图:

LinkedHashMap<Integer, LinkedHashMap<String, Integer>>

但最后的“等等等等”是什么?每个父 ID 是否有多个“子”ID?如果是这样,那么您可能想要某种树(可以通过地图实现,但对其进行抽象似乎是合理的。)

【讨论】:

  • LinkedHashMap&lt;Integer, Map&lt;String, Integer&gt;&gt; 在左侧
  • @assylias 更有可能在右侧作为演员,在左侧您可能想要抽象地图实现。
  • 其实Map&lt;Integer, Map&lt;String, Integer&gt;&gt;在左轴上,我在右轴上说的,对吧? ;-)
  • @assylias 不,在左边我几乎总是使用Map&lt;Integer...etc&gt;&gt;,除非我特别需要传达它保留的插入顺序。
  • 我刚刚更新了我的问题,如果它仍然令人困惑,请告诉我。
【解决方案2】:

在 Java 中,您可以通过以下方式实现:

public class Data {
    public static LinkedHashMap<String, Integer> GUID_VALUES = new LinkedHashMap<String, Integer>();
    public static LinkedHashMap<Integer, Map<String, Integer>> GUID_ID_MAPPING = new LinkedHashMap<Integer, Map<String, Integer>>();

    static {
        Integer someNumber = 0; //or another value, its for initialize the key
        GUID_ID_MAPPING.put(someNumber,GUID_VALUES);
    }
}

不过,我不明白你为什么真的需要这个。我会建议您发布您的功能需求并尝试选择更好的设计来解决问题。

【讨论】:

  • 我经常使用地图的地图(虽然通常是抽象的),这是一个非常典型的结构,不是吗?
  • @DaveNewton 是的,我只是想检查问题是否比这更大,它可能有更好的设计解决方案:)
  • @Luggi,我刚刚更新了我的问题,如果它仍然令人困惑,请告诉我。
  • 我明白 :) 从这个问题中很难看出实际要求是什么:/
【解决方案3】:

您可能想要一个多键映射,就像 Apache Commons Collections 中提供的那样:

http://commons.apache.org/collections/api-release/org/apache/commons/collections/map/MultiKeyMap.html

【讨论】:

  • 嗯,不确定——从问题中看不清楚,但它看起来更像是一个带有嵌套映射的单个键——更像是一棵树。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 2019-04-27
  • 2021-10-13
  • 2015-07-08
相关资源
最近更新 更多