2017-09-26 79 views
-4

我不斷收到java.lang.IndexOutOfBoundsException: Index: 1288, Size: 1287 這是在第一個for循環中參考ArrayList<Formant> stored。我不明白爲什麼ArrayList的容量設置爲1287而不是dp.size爲什麼我的ArrayList未初始化爲我指定的容量?

任何人都可以幫忙嗎? 我已經將最大堆大小增加到10Gb 我嘗試將初始容量設置爲2048(dp的最大大小)。 相關的代碼如下所示:

public Formant[] analyzeBuffer(ArrayList<DataPoint> dp) { 
    //declare variables 
    int count1 = 0; 
    int count2 = 0; 
    ArrayList<DataPoint> stored = new ArrayList<>(dp.size()); 
    Formant[] buffForm = new Formant[12]; 
    //f = new Formant(greatest); 

    //control for infinit loop 
    //while loop checks if datapoint is above threshhold, finds the largest number, and removes all datapoints within a given formant 
    while (!(dp.isEmpty())) { 

     //checks if data point is above threshold, if yes: stores data point in new arraylist 
     for (DataPoint td : dp) { 
      if (td.returnFreq() > threshold) { 
       stored.add(count1, td); 
       count1++; 

      } 
      //checks if data point is the largest number 
      if (td.returnFreq() > greatest) { 
       greatest = td.returnFreq(); 
       f = new Formant(greatest); 
      } 
     } 
     //only removes data points that are formants 
     //removes all data points within a given formant 
     if (f.isFormant) { 
      buffForm[count2] = f; 
      count2++; 
      for (int k = 0; k < stored.size(); k++) { 
       if (stored.get(k).returnFreq() <= (f.determineFormant() + 150) && stored.get(k).returnFreq() >= (f.determineFormant() - 150)) { 
        stored.remove(k); 

       } 
      } 

     } 
     //if freqeuncy is not formant remove all instances of that data point 
     else{ 
      buffForm[count2] = f; 
      count2++; 
      for (int k = 0; k < stored.size(); k++) { 
       if (stored.get(k).returnFreq() == f.freq) { 
        stored.remove(k); 

       } 
      } 

     } 
    } 
    return buffForm; 
} 

回答

1
stored.remove(k); 

你剛纔萎縮stored,所以較大的指標將不再有效。

您需要讓循環向後運行,以便您永遠不會嘗試使用通過刪除移位的索引。

2

ArrayList的容量與其大小不同。它的大小是「這裏有多少個元素」,而容量是「在ArrayList必須重新調整其內部數組的大小之前,我可以放入多少個元素?」

List#add(int idx, E element)增加給定索引處的元素,但它要求List的尺寸(未容量)足夠大:

[拋出] IndexOutOfBoundsException - 如果索引超出範圍(index < 0 || index > size())

相關問題