简体   繁体   中英

Java: Issue with Nested Hashmap

I have a nested LinkedHashMap that looks like this:

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. (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.)

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:
{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:

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.

Let me know if you need further clarification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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