简体   繁体   English

Java:嵌套Hashmap问题

[英]Java: Issue with Nested Hashmap

I have a nested LinkedHashMap that looks like this: 我有一个嵌套的LinkedHashMap看起来像这样:

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

The issue is that only 1 inner map is added per outer map, whereas I am expecting 2. I think the problem is how I'm constructing my map, and over-writing the first inner map with the second. 问题在于,每个外部地图仅添加1个内部地图,而我期望2个。我认为问题在于我如何构建自己的地图,并用第二个内部地图覆盖第一个内部地图。 (To briefly summarize my program, I am mapping each hand onto each finger. The mapping structure needs to be Finger={Right_Hand=[],Left_Hand=[] , not vice versa.) (为简要总结程序,我将每只手映射到每个手指上。映射结构必须为Finger={Right_Hand=[],Left_Hand=[] ,反之亦然。)

The constructor: 构造函数:

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);
        }
}

When I print out the map, though, it looks like this: 但是,当我打印出地图时,它看起来像这样:
{Ring={Left=[]}, Pinky={Left=[]}, Thumb={Left=[]}, Middle={Left=[]}, Index={Left=[]}}

How would I go about creating unique LinkedLists , to allow the map to look like: 我将如何创建唯一的LinkedLists ,以使地图看起来像:
{Ring={Right=[], Left=[]}, Pinky={Right=[], Left=[]}, Thumb={Right=[], Left=[]}, Middle={Right=[], Left=[]}, Index={Right=[], Left=[]}}

Thanks! 谢谢!

I'm going to write what you're currently doing in psuedocode, so hopefully you can see what you're doing wrong: 我将用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

Keep in mind that when you put a key-value entry in a map it replaces any existing entry with the same key. 请记住,当您put键值条目放入地图中时,它将用相同的键替换任何现有条目。

Let me know if you need further clarification. 让我知道您是否需要进一步说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM