My question relates the one method in the PRIME DIRECTIVE exercise that uses all 3 of these. I understand what the program is supposed to do (one method to determine if a number is prime, and the other to store only prime numbers from an array. I get all that.
I also understand how arrays and arrraylists are different. But for some reason my mind can’t wrap around what is happening with these 2 lines.
public ArrayList onlyPrimes(int[] numbers) {
ArrayList primes = new ArrayList();
it’s like merging an arrayList with a method and using an array as a parameter. Can someone break down what is happening here in a very simple example/explanation? I cant understand how it’s all connected.
I’ve done some searches but no one has asked this so far. Here is the whole code for those not familiar with the exercise.
Any help by the pros on here is appreciated!
import java.util.ArrayList;
class PrimeDirective {
public boolean isPrime(int number) {
if (number==2) {
return true;
} else if (number<2) {
return false;
}
for(int i=2;i<number;i++) {
if(number % i==0) {
return false;
}
}
return true;
}
public ArrayList onlyPrimes(int[] numbers) {
ArrayList primes = new ArrayList();
for (int number : numbers) {
if (isPrime(number)) {
primes.add(number);
}
}
return primes;
}
public static void main(String args) {
PrimeDirective pd = new PrimeDirective();
int numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};
System.out.println(pd.isPrime(7));
System.out.println(pd.isPrime(28));
System.out.println(pd.isPrime(2));
System.out.println(pd.isPrime(0));
System.out.println(pd.onlyPrimes(numbers));
}
}