Java:嵌套Hashmap的问题



我有一个嵌套的LinkedHashMap,看起来像这样:

LinkedHashMap<String,LinkedHashMap<String,LinkedList<Long>>> map = new...

问题是每个外部映射只添加1个内部映射,而我期望添加2个。我认为问题在于我如何构造我的映射,并用第二个内部映射覆盖第一个内部映射。(简单地总结一下我的程序,我将每只手映射到每根手指上。映射结构必须为Finger={Right_Hand=[],Left_Hand=[],反之不可以)

构造函数:

Set<String> handNames = new HashSet<String>(Arrays.asList("Left","Right");
Set<String> fingerNames = new HashSet<String>(Arrays.asList("Pinky","Ring","Middle","Index","Thumb");
LinkedHashMap<String, LinkedHashMap<String,LinkedList<Long>>> fingerHandMap = new LinkedHashMap<String, LinkedHashMap<String,LinkedList<Long>>>();
createNestedMap() {
    for (String finger : fingerNames)   
        for (String hand : handNames) {
            LinkedHashMap<String, LinkedList<Long>> handMap = new LinkedHashMap<String, LinkedList<Long>>();
            handMap.put(hand, new LinkedList<Long>());
            fingerHandMap.put(finger, handMap);
        }
}
但是,当我打印出地图时,它看起来像这样:
{Ring={Left=[]}, Pinky={Left=[]}, Thumb={Left=[]}, Middle={Left=[]}, Index={Left=[]}}

我该如何创建唯一的LinkedLists,让地图看起来像:
{Ring={Right=[], Left=[]}, Pinky={Right=[], Left=[]}, Thumb={Right=[], Left=[]}, Middle={Right=[], Left=[]}, Index={Right=[], Left=[]}}

谢谢!

我将在psuedocode中写下您当前正在做的事情,以便您可以看到您做错了什么:

create a new finger hand map
for each finger:
    for each hand:
        create a new hand map
        put an entry mapping the hand to an empty list in the hand map
        put an entry mapping the finger to the hand map in the finger hand map

请记住,当您在映射中put键值项时,它将用相同的键替换任何现有的项。

如果你需要进一步的说明,请告诉我

最新更新