Java 初始化嵌入另一个地图的地图

下午好:


我最近创建了一个特定的类“X”,其中包含单个属性“网络”,该属性被定义为一个映射,该映射使用字符串作为键,另一个映射作为值(双映射)。对于此类,将使用“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 指令时,编译器会自动检测到错误:“预期表达式”。如果可能的话,我想知道在向映射中添加新的键值元素时是否使用了错误的语法,或者是否是映射的初始化导致了错误。


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


达令说
浏览 75回答 1
1回答

倚天杖

你需要做:public class X {&nbsp; &nbsp; private Map<String, Map<String, Integer>> network;&nbsp; &nbsp;//Attribute&nbsp; &nbsp; public X() {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;network = new HashMap<>();&nbsp; &nbsp; //An empty map is created&nbsp; &nbsp; }&nbsp; &nbsp; public int method1() {&nbsp; &nbsp; &nbsp; String string = "sentence"; int number = 2; String string2 = "another";&nbsp; &nbsp; &nbsp; Map<String, Integer> map = new Hashmap<>();&nbsp; &nbsp; &nbsp; map.put(string2, number);&nbsp; &nbsp; &nbsp; network.put(string, map) ;&nbsp;&nbsp; &nbsp; }&nbsp;}这个想法是创建并初始化一个新的 HashMap。然后将键和值对添加到其中。最后将地图插入到封闭的地图中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java