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