1

I am doing some Junit testing on my code, which is meant to produce an arraylist of n prime numbers. I want to compare the created list to a list of known prime numbers in an array, and to do this I need to insert multiple values into an array in my testing class.

So what I have at the moment is

int knownPrimes[] = new int[50];

I know that I could insert values into this array by typing

knownPrimes[1] = 2;
knownPrimes[2] = 3;
etc etc.

I was just wondering how I would do this all in one big chunk, maybe something like:

knownPrimes[] = {2,3,5,7,9...};

but I am not sure of the syntax and I can't find anything on google. Would anyone be able to help me out please ?

Thanks a lot.

2
  • what's wrong with "knownPrimes[] = {2,3,5,7,9...};"? Commented Dec 2, 2010 at 16:44
  • 1
    @Dorin, need an "int" at the start. or add "new int[]" Commented Dec 2, 2010 at 16:47

3 Answers 3

5
int[] knownPrimes = new int[] {2, 3, 5, 7, 9};

As Peter mentioned, the new int[] can be omitted.

Sign up to request clarification or add additional context in comments.

4 Comments

the "new int[]" is not needed.
Cheers. ;) +1 as this works even if you are not initialising it.
...that works if you're not initialising the variable knownPrimes ?! Mind=blown ! Thank you :)
@user476033, yes see the examples in my post.
3

try

int[] knownPrimes = {2,3,5,7,9};

or

int[] knownPrimes;
knownPrimes = new int[] {2,3,5,7,9}

Comments

0

I agree with the solutions posted.

A good book is Thinking in Java, by Bruce Eckel. He covers initialization in Chapter 4, "Initialization and Cleanup," and uses Peter's method. You may buy the latest edition or download an older edition for free.

If the list of knownPrimes is not going to be subclassed, you might want to add the keyword final. If it is class variable and you do not want the value to change after the initialization, you might want to add the keyword static. (I suspect that the list of known primes will be the same throughout the execution of the program.) If you want to access the length of the array, use knownPrimes.length.

Oh, and by the way, 9 should not be in the list of knownPrimes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.