2011-10-25 39 views
0

我基本上把一大塊字符和每個後綴用作鍵,每個鍵指向一個包含索引的ArrayList,其中每個後綴可以找到。我的HashMap <String,ArrayList>的鍵得到了錯誤的值

當我做了HashMap.get(後綴),它給了我這最後添加的關鍵指標,而不是一個我試圖拉(這發生在重複...

這裏它是,

protected HashMap<String, ArrayList<Integer>> makeMap(char[] textStored) 
{ 
    HashMap<String, ArrayList<Integer>> phraseMap = 
      new HashMap<String, ArrayList<Integer>>(); 
    ArrayList<Integer> indexList = new ArrayList<Integer>(); 
    Boolean word = true; 
    String suffix; 
    int wordEndIndex = 0; 
    for (int i = 0; i < textStored.length; i++) { 
     word &= Character.isLetter(textStored[i]); 
     if (word) { 
      for (int h = i + 1;h < textStored.length;h++) { 
       if (!Character.isLetter(textStored[h])) { 
        wordEndIndex = h; 
        break; 
       } 
      }//PULLING THE NEXT SUFFIX vvv 
      //This finds the next word/suffix: 
      suffix = new String(textStored).substring(i,wordEndIndex + 1); 

      //if my hashmap already contains this key: 
      if (phraseMap.containsKey(suffix)) { 
       System.out.println(suffix); 
       indexList = phraseMap.get(suffix); 
       System.out.println(indexList);// This is printing 
        // the wrong info, 
        // telling me my phraseMap.get(suffix) is 
        // using the wrong key, yet 
        // I'm printing out the suffix 
        // directly before that line, 
        // and I'm definitatly inputting 
        // the correct suffix... 
       indexList.add(i); 
       phraseMap.put(suffix,indexList); 
       System.out.println(indexList); 
      } else { 
       // System.out.println(suffix); 
       indexList.clear(); 
       indexList.add(i); 
       phraseMap.put(suffix, indexList); 
       // System.out.println(phraseMap.get(suffix)); 
      } 

     } 
     word = !Character.isLetter(textStored[i]); 
    } 

    return phraseMap; 
} 
+1

縮進大大提高了可讀性 – michael667

回答

5

像你正在使用相同的ArrayList例如在您的整個地圖,也許而不是調用clear你應該實例化一個新ArrayList當後綴不是在映射在我看來。

2

您只有一個ArrayList對象,您可以修改並放入地圖中。

最後,每個鍵都指向相同的列表。

您需要爲每個鍵創建一個數組列表。

+0

'facepalming'的小時,它就這麼簡單!謝啦! – ChrisB92

相關問題