【问题标题】:How to declare Dictionary of Dictionary in java如何在java中声明字典字典
【发布时间】:2025-12-06 16:40:01
【问题描述】:

我有调用在 JAVA Ecllips 开普勒中创建的 SOAP 服务的 C#.Net 代码。从 Web 服务公开的 API(函数)应将 C#.NET 代码中的数据作为参数。我需要发送到 API 的数据是 c#.NET 中的字典字典,如下所示:

Dictionary<string, Dictionary<string, string>> LinksCollection = null;

如何在 Java 中实现这种结构?

我搜索和尝试的内容:

1]以下是在java中实现字典的方法:

1]HashMap

    eg:Map<String, String> map = new HashMap<String, String>();

2]LinkedHashMap
3]Hashtable  

     eg: Dictionary d = new Hashtable();

Is it the right way to implement as follows ?   

 

    Declaring Dictionary: 
       Map<String, String> mapA = new HashMap<String, String>();
     Declaring Dictionary of Dictionary:  
       Map<String, mapA> map = new HashMap<String, mapA>();

【问题讨论】:

  • Map&lt;String, Map&lt;String, String&gt;&gt; map = new HashMap&lt;&gt;() 会是一个更好的起点

标签: java dictionary


【解决方案1】:

除了 Cauis Jard 的 answer,没有一种“最佳”类型可以在所有情况下使用。

  • 如果您不关心订购,那么HashMap 是最明显的选择。如果线程安全不是问题,这可能是您的“默认”选择。

  • 如果您想保留插入顺序,请使用LinkedHashMap

  • 如果要按排序顺序迭代字典键,请使用TreeMap

  • 如果您想从多个线程中使用字典,请根据您的要求从以下选择:

    • ConcurrentHashMap
    • SkipListMap
    • Collections.synchronizedMap(...)
    • Collections.unmodifiableMap(...)

您也可以使用Properties 甚至是旧的/过时的HashtableDictionary 类。

【讨论】:

    【解决方案2】:

    这就像在 C# 中一样,除了单词 HashMap 而不是 Dictionary

    HashMap<String, HashMap<String, String>>
    
    Map<String, String> mapA = new HashMap<String, String>();
    Map<String, mapA> map = new HashMap<String, mapA>();
    

    不是,因为 mapA 是一个实例,而不是一个类型。这在 C# 中也行不通

    //no
    var d = new Dictionary<string, string>();
    var e = new Dictionary<string, d>(); //error: `d` is a variable, but is used like a type
    

    【讨论】: