Generating Array with some specific values

时间:2015-07-28 15:58:37

标签: java algorithm

I have to generate prime number. For this reason I have to initialize all array elements to -1. From c/c++, I came to know I have to initialize them by using a for loop. Please see the code below

public static void main(String[] args){

        final int SIZE = 1000;
        int[] intArray = new int[SIZE];
        Arrays.fill(intArray, -1);

        for(int i=0; i<SIZE; i++){
            intArray[i] = -1;
        }

        for(int i = 0; i<SIZE; i++){
            System.out.println(intArray[i]);
        }

    }

In java is there any better way to do this?

2 个答案:

答案 0 :(得分:2)

Well, Arrays.fill(intArray, -1); already fills your array, so there's no need for the redundant for loop following that statement.

You can also just remove your final int SIZE, and say int[] intArray = new int[1000];. When you need to get the length/size of the array, you can just say intArray.length.

答案 1 :(得分:1)

You can only use Arrays.fill(int[] a, int val) method like this -

Arrays.fill(intArray, -1); 

The Arrays.fill() populates the array - intArray with the specified value val. So you don't need to initialize the intArray using the for loop.

And one more thing, in c++ it is also possible to initialize array with some value like this, without using the for loop. See here