Java 我的HashMap<;字符串,ArrayList>';s的关键是获取错误的值

Java 我的HashMap<;字符串,ArrayList>';s的关键是获取错误的值,java,key,hashmap,Java,Key,Hashmap,我基本上是取一大块字符,使用每个后缀作为键,每个键指向一个数组列表,其中包含可以找到每个后缀的索引 当我做HashMap.get(后缀)时,它会给我最后添加的键的索引,而不是我试图拉取的键的索引(这发生在重复项上 在这里 protected HashMap<String, ArrayList<Integer>> makeMap(char[] textStored) { HashMap<String, ArrayList<Integer>>

我基本上是取一大块字符,使用每个后缀作为键,每个键指向一个数组列表,其中包含可以找到每个后缀的索引

当我做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;
}
受保护的HashMap makeMap(char[]textStored)
{
HashMap短语映射=
新的HashMap();
ArrayList indexList=新的ArrayList();
布尔字=真;
字符串后缀;
int-wordEndIndex=0;
for(int i=0;i
在我看来,您在整个地图中使用的是相同的
ArrayList
实例。也许您不应该调用
clear
,而应该在后缀不在地图中时实例化一个新的
ArrayList

您只有一个ArrayList对象可以修改并放入地图中

最后,每个键都指向同一个列表


您需要为每个键创建一个数组列表。

缩进极大地提高了“facepalming”的可读性小时,就这么简单!谢谢!