2015-06-24 133 views
2

所以,當我運行這個方法時,我總是得到數組索引超出界限的錯誤。我很熟悉這個錯誤,但我不明白爲什麼會發生這種情況。下面是代碼:數組索引超出界限錯誤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語句行。但是,如果您在上面查看,則可以看到上面的語句完全相同,但不會產生錯誤。請幫忙!

+4

您是否試過踏入代碼一行一行? – sstan

+0

從你的代碼中,我得到的印象是你認爲dupeWordList是wordList的副本(它不是)? – FatalError

+0

我試圖讓它成爲重複的,是的。 –

回答

0

我能想到的唯一的事情就是你遇到了某種無限循環,你的條件是while(tempWord.getValue() == nextWord.getValue()) {。也許這兩個值可以停留在"the"

如果發生這種情況,那麼變量i將增加到它將經過Integer.MAX_VALUE並且開始具有負值的點。

如果發生這種情況,則條件if(i+1 < dupeWordList.size() - 1) {將成爲true,但您的值爲i將對您的列表無效,並將拋出超出界限的異常。

(順便說一句,你真的應該使用equals()比較字符串,不==

+0

高可能性 –

+0

找出來了,這是一個掛在「the」上的問題。我改變了這一行來破解並從那裏出錯。用==代替.equals(),我剛剛意識到這一點。我習慣於c#,所以我從那裏獲得。 –

0

您正在爲循環行和while循環內部遞增索引i。這聽起來有點「不 - 不」。你確定知道你在那裏做什麼?我有一種直覺,你不應該那樣做。

+0

我知道在那段代碼中,我需要根據我現有的內容改變,但我可能會採取錯誤的做法...?這會導致錯誤還是僅僅是那種看起來不合常理的事情。 –

0

我想你指的是這段代碼?

if(i+1 < dupeWordList.size() - 1) { 
     nextWord = dupeWordList.get(i+1); 
} 

所以,dupeWordList.size()-1是可以參考的最後一個索引位置。您引用i+1,這比最後一個索引小(因爲if語句條件)。所以,你正試圖get這個詞在最後一個詞之前。

按照javadocs,就會得到一個IndexOutOfBoundsException如果:

IndexOutOfBoundsException - 如果索引超出範圍(index < 0 || 指數> =尺寸())

由於您的if語句保證索引不是> = size(),那麼唯一的可能性必須是該索引< 0.