简体   繁体   中英

Generating Array with some specific values

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM