1

I want to create an int array with 999 elements, each of which has value 999. Is there a way to initialize an int array during declaration instead of iterating through each element and setting its value to 999?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user246392
  • 2,661
  • 11
  • 54
  • 96
  • Possible duplicate of [How to initialize all members of an array to the same value?](https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value) – Vivek Shankar Aug 08 '17 at 09:44

3 Answers3

5

If the array was small, e.g. only 3 items, you could do as follows::

int[] ints = { 999, 999, 999 };

But if it grows and you don't want to repeat yourself, then better use Arrays#fill(). It hides the for loop away for you.

int[] ints = new int[999];
Arrays.fill(ints, 999);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

This is not possible as you ask, you can however use Arrays.fill() to fill it and use an initialiser block to call that method:

class MyClass {
    private int [] myInts = new int[999];

    {
        Arrays.fill(myInts, 999);
    }

    // ...
}
rsp
  • 23,135
  • 6
  • 55
  • 69
2

Of course, it is:

int[] tab = {999, 999, 999, 999, 999, 999, 999, 999, 999, 999, ... };

You just have to type 999 for the number of elements you want, in this case 999 times)

Nick is tired
  • 6,860
  • 20
  • 39
  • 51