0

I don't get how can it be out of bounds if I bound i by the array size. I get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 116, Size: 116

eratosthenes(ArrayList <Integer> array) checks for primal every element and deletes it if true, then the process is repeated for the next remained element.

package arrays;
import java.util.*;

public class Examples {


    public static void main(String[] args) {

        ArrayList <Integer> array = getFilledArrayList(2, 1000);
        eratosthenes(array);
        System.out.println(array.toString());


    }


    private static void eratosthenes(ArrayList <Integer> array) {       
        int index = 0;
        int primal = array.get(index);
        while (index < array.size() - 1) {

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

                if (array.get(i) % primal == 0) array.remove(i);
            }
            index++;
            primal = array.get(index);
        }

    }

    private static ArrayList <Integer> getFilledArrayList(int start, int stop) {
        ArrayList <Integer> array = new ArrayList();
        for (int i = start; i < stop + 1; i++) {
            array.add(i);
        }
        return array;
    }

}
electroiv
  • 168
  • 1
  • 2
  • 12
  • the for loop can remove elements from the list to the point where index < array.size() - 1 is false inside the while and your index becomes greater than your array.size(). or in this case, it's equal to it and throws the exception – RAZ_Muh_Taz Apr 03 '18 at 15:44
  • Add another check before you try to increase the index like this if(index + 1 < array.size()){ primal = array.get(++index);} That way you verify that you can find the next primal without throwing an index out of bounds exception – RAZ_Muh_Taz Apr 03 '18 at 15:55

2 Answers2

0

Array bounds are 0-indexed, meaning that the first element in an array is found at index 0. Therefore, the last index that is within the bounds of an array is the array size minus 1. Thus, the bounds of an array in Java span from [0, length - 1], or stated another way, [0, length).

The culprit is the following snippet:

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

    if (array.get(i) % primal == 0) array.remove(i);
}
index++;
primal = array.get(index);

If array.remove(i) is called within the loop, the number of values in array is reduced. Paired with the increment of index in the index++ line, this may push index beyond the bounds of array causing an IndexOutOfBoundsException.

For example, if array has a length of 1000 and index has a value of 998, calling array.remove(i) causes the length of array to be reduced to 999. The increment of index causes index to have a value of 999, which is equal to the length of array, resulting in an IndexOutOfBoundsException.

Justin Albano
  • 3,809
  • 2
  • 24
  • 51
-1

array.size() -1, since the array index starts at zero

pecks
  • 318
  • 1
  • 2
  • 9