Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfBoundsException

Tags:

java

exception

Hi this code will return indexoutofboundsException and really I don't know why? I want to remove those objects from pointlist which are as the same as an object in the list.

    public void listOfExternalPoints(List<Point> list) {
    System.out.println(list.size());
    System.out.println(pointList.size());
    int n = pointList.size();
    for (int i = pointList.size() - 1; i >= 0; i--) {
        for (int j = 0; j < list.size(); j++) {
            if (pointList.get(i)==(list.get(j))) {
                pointList.remove(i);
                n--;
            }
        }
    }

}

Also the out put of println will be :

54
62

Also the exception:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 60, Size: 60
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at ConvexHull.BlindVersion.listOfExternalPoints(BlindVersion.java:83)

thanks.

like image 230
user472221 Avatar asked Dec 30 '25 08:12

user472221


2 Answers

hey, you removed some elements from the list. So the list is smaller than it was at the beginning of the loop.

I suggest you to use:

pointList.removeAll(list)

Or an iterator.

like image 182
scheffield Avatar answered Jan 02 '26 02:01

scheffield


When you do pointList.remove(i), you should break from the inner loop. Otherwise, it will try to index pointList.get(i), which you just removed, again on the next iteration of the loop, which is why are you getting the exception.

When arrayLists remove elements, that element is taken out, and all elements after it gets shifted down. So if you remove index 3 and there are only 4 elements, the new arrayList only has size 3 and you try to get index 3, which is out of bounds.

EDIT: A better way to do this is:

for(Point p : list) {
    pointList.remove(p);
}

It will have the same efficiency, but more correct, I think. Remember that == compares references for the same object. Where as the remove method uses .equals to check for equality, which is what I assume you want.

like image 42
shoebox639 Avatar answered Jan 02 '26 00:01

shoebox639