What is the difference between Array and ArrayList to get prime numbers?

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.

+6
source share
3 answers

Instead

 primeNumbers.add(j, false); 

you should use

 primeNumbers.set(j, false); 

since add() adds a new element at the specified position (this means that the ArrayList grows by one element), but set() sets only the value of the element at the specified position.

+7
source
 primeNumbers.add(j, false); 

adds an element to the list of arrays and moves all elements with an index> = j to the right [including the previous element j ], and:

 primeNumbers[j]= false 

overrides the existing element j and does not change the elements.

Perhaps you are looking for ArrayList.set() instead of ArrayList.add()

+4
source

The difference between Array and ArrayList :

  • An array implementation is a simple fixed size array, but an ArrayList implementation is a dynamic size array.
  • An array can contain both primitives and objects, but an ArrayList can only contain elements of an object
  • You cannot use generics with an array, but ArrayList allows you to use generics to ensure type safety.
  • You can use the length variable to calculate the length of the array, but the size () method to calculate the size of the ArrayList.
  • An array assignment operator to store elements, but ArrayList uses add () to insert elements.
0
source

Source: https://habr.com/ru/post/914326/


All Articles