Exception when removing elements from ArrayList?

Viewed 1143

I am filling an ArrayList al with random integers. Then when I try to remove them i'm getting these errors:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5000 out-of-bounds for length 5000 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.remove(ArrayList.java:517) at a2_40038465.ListTester.main(ListTester.java:137)

This is my code:

System.out.println("-----------------------------------------------------------------------------");
    System.out.println("Inserting at the beginning...");
    long startTime4 = System.currentTimeMillis();

    for(int i=0; i<10000; i++) {
        al.add(0, rand.nextInt(20001));
    }

    long endTime4 = System.currentTimeMillis();
    long elapsed4 = endTime4 - startTime4;
    System.out.println("Time elapsed: " + elapsed4);
    System.out.println("-----------------------------------------------------------------------------");

    System.out.println("Removing from beginnig...");
    long startTime19 = System.currentTimeMillis();

    for(int i=0; i<10000; i++) {
        al.remove(i);
    }

    long endTime19 = System.currentTimeMillis();
    long elapsed19 = endTime19 - startTime19;
    System.out.println("Time elapsed: " + elapsed19);
    System.out.println("-----------------------------------------------------------------------------");
1 Answers
al.remove(i);

removes the element at index i. In the beginning of the removal your list has 10000 items. After the first 5000 iterations of the loop your list only has 5000. Then you call al.remove(5000) which in an array of size 5000 is no longer allowed. In the step before you had 5001 elements in the list and called al.remove(4999) which was allowed.

Use remove(0) in the loop or clear() without any loop to remove all elements.

Your main mistake is probably thinking that remove(0) and a subsequent remove(1) removes the first 2 elements of the array. But that is not the case. What actually happens is that the first statement removes the first element, after that the originally second element becomes the first, the third one becomes the second, etc. So remove(1) after that removes the originally third elment. You would never remove the originally second element (and many others) if you continued that logic.

Related