下午好:
我最近创建了一个特定的类“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/