开发者

How do I define an array with multiple values?

开发者 https://www.devze.com 2023-01-28 05:36 出处:网络
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 n

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.


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

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


try

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

or

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消