I am getting an Array Index out of Bounds error, however I am unable to see how I


#1

I am getting an Array Index out of Bounds error, however I am unable to see how I am aceesing an out of Index position. Here is my code:
public class Solution {
public ArrayList sieve(int a) {
int i,j;
// ArrayList res=new ArrayList<>();
ArrayListPrimes=new ArrayList<>(a+1);

for(i=0;i<=a;i++)
{
Primes.set(i,1);
}
Primes.set(0,0);
Primes.set(1,0);

for(i=2;i<=Math.sqrt(a);i++)
{
if(Primes.get(i)==1)
for(j=2*i;j<=a;j+=i)
{
Primes.set(j,0);

}
}
return Primes;
}
}
Thanks in advance.


#2

This is because you wrote new ArrayList<>(some number) … When you write this, you do not mean that the arraylist will be of that size(some number)… rather it is the capacity i.e. how much can the arrayList hold… size of an arrayList increases only when you have added elements in the list … See this for more clarity: