Ahmed Nassar Ahmed Nassar - 3 years ago 146
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) {
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);

}
}

}
}


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.

Answer Source

Instead of

primeNumbers.add(j, false);

you should use

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download