The problem is simple, I need to remove all primes from an arraylist(called al) and print it.
I created a second arraylist(called noPrime) to store all the non-primes, and then stored the noPrime's reference in al and printed it twice. Once inside the solution() method and once in the main method AFTER solution() was already called.
Yet,
When I print the array al in the solution method, it outputs the correct answer.
When I print it in the main method, after calling the solution method, it outputs the incorrect answer.
Example:
Original = [3, 12, 13, 15]
first printing = [12, 15]
second printing = [3, 12, 13, 15]
I suspect it is because noPrime has been declared within solution() and it gets destroyed once the solution() has returned. So al, which was holding the reference of noPrime, also gets destroyed? And it comes back to holding its original reference?
Why is this happening?
what does al = noPrime really do?
What I have tried:
import java.io.*;
import java.util.*;
public class Main {
private static boolean isPrime(int num)
{
int rootnum = (int)Math.sqrt(num);
for(int i = 2; i <= rootnum; i++ )
{
if(num%i == 0)
return false;
}
return true;
}
public static void solution(ArrayList<Integer> al){
ArrayList<Integer> noPrime = new ArrayList<>();
int size = al.size();
for(int i = 0; i < size ; i++)
{
int num = al.get(i);
if(!isPrime(num))
noPrime.add(num);
}
al = noPrime;
System.out.println(al);
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
ArrayList<Integer> al = new ArrayList<>();
for(int i = 0 ; i < n; i++){
al.add(scn.nextInt());
}
System.out.println("Original = " + al);
solution(al);
System.out.println(al);
}
}