public static int createArray(int theListSize)
{
ArrayList<Integer> possiblePrimeNum = new ArrayList<Integer>();
for (int i=0; i<=theListSize; i ) //simply creates the array
{
possiblePrimeNum.add(i, i 2);
}
return possiblePrimeNum;
}
I don't understand this code. I mean that I understand what I'm going to do, but I don't know why the array won't return. What's wrong here?
possiblePrimeNum=createArray(theListSize);
CodePudding user response:
You declared this method as returning a single int
value, a single number, and a primitive (not an object).
An ArrayList
is a collection of numbers, Integer
objects (not primitives).
You said:
Dynamic 1D Array
I do not know what you mean by "Dynamic".
An array in Java is not the same as an ArrayList
. The first is a built-in basic type in Java. The second is a class found in the Java Collections Framework, bundled with all Java distributions.
- Tutorial on arrays by Oracle
- Tutorial on Collections by Oracle
You asked:
I mean that I understand what I'm going to do, but I don't know why the array won't return.
Change your method to return a List
of Integer
objects rather than a single int
. Something like this.
public static List < Integer > possiblePrimes ( final int countOfPrimes )
{
List < Integer > possiblePrimes = new ArrayList < Integer >( countOfPrimes );
for ( int i = 0 ; i <= countOfPrimes ; i )
{
possiblePrimes.add( i , i 2 );
}
return List.copyOf( possiblePrimes ); // Return a unmodifiable list, as a general best practice.
}
Call that method like this.
List < Integer > maybePrimes = App.possiblePrimes( 7 );
System.out.println( "maybePrimes = " maybePrimes );
When run:
maybePrimes = [2, 3, 4, 5, 6, 7, 8, 9]
I think your algorithm for finding candidate primes needs some more work.