-1

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
nhb.sajol
  • 37
  • 8
  • 5
    why do you have to initialize an array with -1? – depperm Jul 28 '15 at 15:59
  • 4
    BTW, in C++ you'd better use `std::vector` that has a special constructor for this: `std::vector intArray(SIZE, -1)`. – Petr Jul 28 '15 at 16:00
  • This isn't java specific, but try to follow a consistent way of spacing operators and operands. Like, in the first for loop you have `i=0` in the second one `i = 0`. Either follow the first style or the second one. Don't mix. – Ghazanfar Jul 28 '15 at 16:04
  • 2
    Why did you use `Arrays#fill`? What do you think that does? Why do you think so? – Sotirios Delimanolis Jul 28 '15 at 16:05
  • @Petr, Thanks. I did not knew it. – nhb.sajol Jul 28 '15 at 16:06
  • 1
    Look at the implementation of Arrays.fill, it's just a for loop as well, other for readablity and "code-sleakness", there is no difference... just FYI http://developer.classpath.org/doc/java/util/Arrays-source.html – Dänu Jul 28 '15 at 16:32
  • This looks like a more appropriate question for codereview.stackexchange.com – Kirby Jul 28 '15 at 16:34
  • If you would post about this on Code Review, post your whole prime-number-generation code. I'm sure that in the end, you'll end up throwing this part of the code away. – Simon Forsberg Jul 28 '15 at 16:39

2 Answers2

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.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57
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

Community
  • 1
  • 1
Razib
  • 10,965
  • 11
  • 53
  • 80