【问题标题】:My HashMap<String, ArrayList>'s Key is getting the wrong values我的 HashMap<String, ArrayList> 的键得到了错误的值
【发布时间】:2011-10-25 08:40:22
【问题描述】:

我基本上采用一大块字符并使用每个后缀作为键,每个键指向一个 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;
}

【问题讨论】:

  • 缩进大大提高了可读性

标签: java key hashmap


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 数小时的“捂脸”,就这么简单!谢谢大佬!
    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2013-10-05
    • 2014-01-02
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多