java - 我的 HashMap<String, ArrayList> 的键获取了错误的值

标签 java key hashmap

我基本上采用一大块字符并使用每个后缀作为键,每个键都指向一个 ArrayList,其中包含可以找到每个后缀的索引。

当我执行 HashMap.get(suffix) 时,它会给我最后添加的键的索引,而不是我试图提取的键的索引(这发生在重复项上......

在这里,

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

最佳答案

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

关于java - 我的 HashMap<String, ArrayList> 的键获取了错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7886736/

相关文章:

key - AHK 长按替代键

java - HashMap 到 DefaultListModel

java - 阐明 Java 实现 HashSet/HashMap 背后的事实

java - 如果 doc 值用于 Elasticsearch 中的某个字段,那么存储该字段是否多余?

java - 如何通过从继承转向组合来简化 Java 代码

java - 无法让小程序读取文本文件

java - 如何使用 setContentView(new Activity(this)); 以编程方式创建 admob 横幅不使用xml?

ruby-on-rails - 如何在 rails 中向我的表追溯添加主键?

java - 如何删除磁盘上的 Redis 键?

hashmap - 如何重写HashMap.java中的一些函数