所以,當我運行這個方法時,我總是得到數組索引超出界限的錯誤。我很熟悉這個錯誤,但我不明白爲什麼會發生這種情況。下面是代碼:數組索引超出界限錯誤Java
public void setFrequencies() {
List<Word> dupeWordList;
dupeWordList = wordList;
dupeWordList.removeAll(Collections.singleton(null));
Collections.sort(dupeWordList);
for(int i = 0; i < dupeWordList.size(); i++) {
int count = 1;
Word tempWord = dupeWordList.get(i);
tempWord.setFrequency(count);
Word nextWord = dupeWordList.get(dupeWordList.size() - 1);
if(i+1 < dupeWordList.size() - 1) {
nextWord = dupeWordList.get(i+1);
}
while(tempWord.getValue() == nextWord.getValue()) {
count++;
i++;
tempWord.setFrequency(count);
for(int e = 0; e < count - 1; e++) {
Word middleWord = new Word();
if((i-count+1)+1+e < dupeWordList.size() - 1) {
middleWord = dupeWordList.get((i-count+1)+1+e);
}
middleWord.setFrequency(count);
}
if(i+1 < dupeWordList.size() - 1) {
nextWord = dupeWordList.get(i+1);
} else {
nextWord.setValue("the");
}
}
}
List<Word> reSortedList = wordList;
Word fillWord = new Word();
fillWord.setFrequency(0);
fillWord.setValue(null);
Collections.fill(reSortedList, fillWord);
for(int i = 0; i < dupeWordList.size(); i++) {
Word word = dupeWordList.get(i);
int wordOrder = word.getOrigOrder();
reSortedList.set(wordOrder, word);
}
setWordList(reSortedList);
}
它有問題的線是包含nextWord = dupeWordList.get(i+1)
if語句行。但是,如果您在上面查看,則可以看到上面的語句完全相同,但不會產生錯誤。請幫忙!
您是否試過踏入代碼一行一行? – sstan
從你的代碼中,我得到的印象是你認爲dupeWordList是wordList的副本(它不是)? – FatalError
我試圖讓它成爲重複的,是的。 –