1

我有一个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=[]}}

我将如何创建 unique LinkedLists,以使地图看起来像:
{Ring={Right=[], Left=[]}, Pinky={Right=[], Left=[]}, Thumb={Right=[], Left=[]}, Middle={Right=[], Left=[]}, Index={Right=[], Left=[]}}

谢谢!

4

1 回答 1

1

我将用伪代码写出你目前正在做的事情,所以希望你能看到你做错了什么:

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在映射中使用键值条目时,它会用相同的键替换任何现有条目。

如果您需要进一步说明,请告诉我。

于 2013-04-26T22:17:40.517 回答