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?
3 Answers
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);
1 Comment
Peter Lawrey
This uses a for loop for you. You can create a helper method which will create a new array filled with a value.