I was solving a problem with prime numbers, I found a solution using arrays, but I wanted to use a list of arrays for some problems, one of them is to understand Arraylist well. but I found that the results do not match when I use arraylist, here are 2 codes:
// use arrays
import java.util.Arrays; public class Prime { public static void main(String[] args) { primeNumber(100); } public static void primeNumber(int end) { boolean primeNumbers[] = new boolean[end]; for (int i = 0; i < end; i++) { primeNumbers[i] = true; } for (int i = 2; i < primeNumbers.length; i++) { if (primeNumbers[i] ) { for (int j = i+i; j < primeNumbers.length; j += i) { primeNumbers[j]= false; } } } for (int j = 2; j < primeNumbers.length; j++) { if (primeNumbers[j]) { System.out.println(j); } } } }
// Using ArrayList
import java.util.ArrayList; public class Prime { public static void main(String[] args) { primeNumber(100); } public static void primeNumber(int end) { ArrayList<Boolean> primeNumbers = new ArrayList<Boolean>(); for (int i = 0; i < end; i++) { primeNumbers.add(i,true); } for (int i = 2; i < primeNumbers.size(); i++) { if (primeNumbers.get(i) ) { for (int j = i+i; j < primeNumbers.size(); j += i) { primeNumbers.add(j, false); } } } for (int j = 2; j < primeNumbers.size(); j++) { if (primeNumbers.get(j)) { System.out.println(j); } } } }
May I find out what I did using Arraylist, and if I wanted to use arraylist for the same result, what should I do.
Many thanks for the help.
source share