2013-04-26 88 views
1

我有一個嵌套的LinkedHashMap,看起來像這樣:的Java:問題與嵌套的Hashmap

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=[]}}

謝謝!

回答

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鍵值項在地圖中,它用相同的鍵替換任何現有的條目。

讓我知道你是否需要進一步澄清。

+0

我還是沒有看到它。我覺得很愚蠢,但我今天可能已經盯着這個節目太久了。任何線索? – 2013-04-26 22:26:15

+0

@Adam_G查看我的編輯。基本上你用「左」地圖覆蓋每個「右」地圖。你真的想再次查找相同的地圖並添加到它。 – 2013-04-26 22:27:22

+0

但是,如果其中一個鍵是「正確」而另一個是「左」,爲什麼我會覆寫它? (我知道你是對的,我只是沒有看到它。) – 2013-04-26 22:35:27