Sorry for the silly question, but I cannot seem to find an answer on google. I have written a class, and within the class there is a constructor which creates an arraylist, in the same class there is a method which iterates through the array list by creating an iterator object. As my code stands, however, it is not recognizing the arraylists name, should I store the array list in a class variable, or pass it into the method as an argument ?
What is usually best practice here as this is something that is always getting me ?
My code is as follows if you can’t follow my somewhat convuluted explanation ! Apologies ! Thanks a lot for reading 🙂
import java.util.*;
public class Primes {
public Primes( int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
//how do I get the above...
int index = 2;
while (index != listOfPrimeNumbers.size())
{
if (isPrime(index))
{
listOfPrimeNumbers.add(index);
}
index++;
}
}
public static boolean isPrime(int candidateNo) {
Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
//in here ! ?
i=2;
while ( iter.hasNext( ) ) {
if (candidateNo%i==0 && i!=1) {
return false;
}
else
return true;
}
}
(Also, if you see anything horrifically wrong with my code please don’t be afraid to call me out on it, the more constructive criticism the better!)
}
You define a private var for your ArrayList and initalize this variable in your Constructor.
Now you can access the list inside your Class 🙂
hope that helps.