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;
}
}