Java 初始化嵌入另一个 map 的 map

标签 java dictionary hashmap initialization

下午好:

我最近创建了一个特定的类“X”,其中包含单个属性“network”,该属性被定义为一个映射,该映射使用字符串作为键,另一个映射作为值(双映射)。对于此类,将使用“hashmap”实现。

该类大致如下所示:

public class X {
    private Map<String, Map<String, Integer>> network;   //Attribute

    public X() {        
        network = new HashMap<>();    //An empty map is created
    }

    public int method1 {
        String string = "sentence"; 
        int number = 2; 
        String string2 = "another";
        network.put(string, <string2, number>);    //NOT WORKING - wrong syntax/wrong initialization?
    }    
}

但是,当我执行函数中包含的 network.put 指令时,编译器会自动检测到错误:“需要表达式”。如果可能的话,我想知道在向映射中添加新的键值元素时是否使用了错误的语法,或者是否是映射的初始化导致了错误。

非常感谢所有帮助。 谢谢。

最佳答案

你需要做:

public class X {
    private Map<String, Map<String, Integer>> network;   //Attribute

    public X() {        
       network = new HashMap<>();    //An empty map is created
    }
    public int method1() {
      String string = "sentence"; int number = 2; String string2 = "another";
      Map<String, Integer> map = new Hashmap<>();
      map.put(string2, number);
      network.put(string, map) ; 
    }
 }

这个想法是创建并初始化一个新的 HashMap。然后将键和值对添加到其中。最后将 map 插入到封闭的 map 中。

关于Java 初始化嵌入另一个 map 的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58258760/

相关文章:

ReSTLet 2.1-M4 以上版本的 Java 序列化问题

java - 有没有办法使用 JMX 代码来捕获网络异常?

python - 将 txt 文件中的值列表转换为字典

java - map 框安卓 : How to get directions from current location to a destination you choose?

python - 在将 python 集与自定义对象相交时选择要保留的元素

java - 如何在java中转义],[序列?

java - 分块传输视频帧然后重新组合它们?

Javascript 面向对象的语法引用

JAVA - 使用字符串创建HashMap

java - 具有多个值的键