2011-10-25 31 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

相关问题