Ahmed Nassar - 3 years ago 141
Java Question

# what is difference between Array and ArrayList to get Prime numbers?

i was solving problem about the prime numbers, i found solution using Arrays, but i wanted to use the array list for some issues, one of them is to understand the Arraylist well. but i found that the results are not the same when i use the arraylist, here are the 2 Codes:

//using Arrays

``````import java.util.Arrays;
public class Prime {
public static void main(String[] args) {
}
public static void primeNumber(int end) {
for (int i = 0; i < end; i++) {
}
for (int i = 2; i < primeNumbers.length; i++) {
for (int j = i+i; j < primeNumbers.length; j += i) {
}
}
}
for (int j = 2; j < primeNumbers.length; j++) {
System.out.println(j);

}
}
}
}
``````

//Using ArrayList

``````import java.util.ArrayList;
public class Prime {
public static void main(String[] args) {
}

public static void primeNumber(int end) {
for (int i = 0; i < end; i++) {
}
for (int i = 2; i < primeNumbers.size(); i++) {
for (int j = i+i; j < primeNumbers.size(); j += i) {
}
}
}
for (int j = 2; j < primeNumbers.size(); j++) {
System.out.println(j);

}
}

}
}
``````

Can i know what is the wrong i did with using the Arraylist, and if i wanted to use the arraylist for the same result what should i do.

Great thanks for the help.

``````primeNumbers.add(j, false);
``````primeNumbers.set(j, false);
since `add()` adds a new element at the specified position (meaning the ArrayList grows by one element), but `set()` only sets the value of the element at specified position.