[英]Why is my ArrayList not initialized to the capacity i specify?
我不斷收到java.lang.IndexOutOfBoundsException: Index: 1288, Size: 1287
這是對ArrayList<Formant> stored
在第一個 for 循環中的ArrayList<Formant> stored
引用。 我不明白為什么 ArrayList 的容量被設置為 1287 而不是dp.size
有人能幫忙嗎? 我已將最大堆大小增加到 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;
}
ArrayList 的容量與其大小不同。 它的大小是“其中有多少元素”,而容量是“在 ArrayList 必須重新調整其內部數組的大小之前,我可以放入多少個元素?”
List#add(int idx, E element)
在給定的索引處添加一個元素,但它要求 List 的大小(不是容量)足夠大:
[throws]
IndexOutOfBoundsException
- 如果索引超出范圍(index < 0 || index > size())
stored.remove(k);
您只是縮小了stored
,因此較大的索引不再有效。
你需要讓你的循環向后運行,這樣你就永遠不會嘗試使用因刪除而移動的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.