有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java My 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;
}

共 (2) 个答案

  1. # 1 楼答案

    在我看来,您在整个地图中使用的是相同的ArrayList实例。当后缀不在映射中时,也许应该实例化一个新的ArrayList,而不是调用clear

  2. # 2 楼答案

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

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

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