我试图建立一个间隔树。在这一部分中,我必须按升序排列所有左端点,并按升序排列所有右端点,并将它们放置在单点列表中(无重复)。但是,当我尝试将正确的端点合并到点列表中时,总是收到indexOutOfBounds异常。我已确保不会发生这种情况,但是无论如何都会发生这种情况。我在这里不明白什么?

public static ArrayList<Integer> getSortedEndPoints(ArrayList<Interval> leftSortedIntervals, ArrayList<Interval> rightSortedIntervals) {

    ArrayList<Integer> result = new ArrayList<Integer>();

    for (int i = 0 ; i < leftSortedIntervals.size() ; i++ ) {

        if (i >= 1 && leftSortedIntervals.get(i-1).leftEndPoint != leftSortedIntervals.get(i).leftEndPoint ) {
        result.add(leftSortedIntervals.get(i).leftEndPoint);
        }
        else if (i == 0) {

            result.add(leftSortedIntervals.get(i).leftEndPoint);

        }

    }
    result.ensureCapacity(rightSortedIntervals.size()*2);
    for (int j = 0 ; j < rightSortedIntervals.size(); j++) {
        boolean duplicate = false;
        int size = result.size()-1;
        int temp = rightSortedIntervals.get(j).rightEndPoint;
        while (size >= 0 && result.get(size) >= rightSortedIntervals.get(j).rightEndPoint ) {
            if (result.get(size) == rightSortedIntervals.get(j).rightEndPoint) {
                duplicate = true;
                break;
            }
            else {
                result.set(size+1, result.get(size));

                size--;
            }


        }
        if (duplicate = true) {

            continue;

        }
        else {
        result.add(size, temp);
        }
    }


    return result;
}


该行发生错误:

else {
            result.set(size+1, result.get(size));

            size--;
        }

最佳答案

你有:

int size = result.size() - 1;
// ...
result.set(size + 1, result.get(size));
size--;


因此,错误将每次发生:在第一次迭代中,size + 1 == result.size(),因此您无法调用result.set(size+1, anything)

关于java - Arraylist不断抛出IndexOutOfBounds,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15395019/

10-13 04:17