Java 为什么我的ArrayList没有初始化到我指定的容量?
我一直得到一个java.lang.IndexOutOfBoundsException:索引:1288,大小:1287 这是对存储在第一个for循环中的ArrayList的引用。我不明白为什么ArrayList的容量被设置为1287而不是dp.size 有人能帮忙吗? 我已将最大堆大小增加到10Gb 我尝试将初始容量设置为2048,即dp的最大大小。 相关代码如下所示:Java 为什么我的ArrayList没有初始化到我指定的容量?,java,arraylist,Java,Arraylist,我一直得到一个java.lang.IndexOutOfBoundsException:索引:1288,大小:1287 这是对存储在第一个for循环中的ArrayList的引用。我不明白为什么ArrayList的容量被设置为1287而不是dp.size 有人能帮忙吗? 我已将最大堆大小增加到10Gb 我尝试将初始容量设置为2048,即dp的最大大小。 相关代码如下所示: public Formant[] analyzeBuffer(ArrayList<DataPoint> 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重新调整其内部数组的大小之前我可以放入多少元素 在给定索引处添加元素,但它要求列表的大小不能足够大: [抛出]IndexOutOfBoundsException-如果索引超出范围,则索引<0 | |索引>大小
stored.remove(k);