Trying to find the easiest way to fill an array with some values starting at 23 in descending order. I have the code below but not getting the result i am looking for:
int[] arr = new int[8];
int i = 24;
Arrays.fill(arr, --i);
System.out.println(Arrays.toString(arr));
output now
[23, 23, 23, 23, 23, 23, 23, 23]
expected
[23, 22, 21, 20, 19, 18, 17, 16]
How to fill an array easily and get the expected output, if possible without a for/while loop?
>Solution :
Why not simply use a for loop?
for (int j = 0; j < arr.length; j++) {
arr[j] = i;
i--;
}
You can also use the Arrays.setAll function
Arrays.setAll(arr, (index) -> i - index);
By the way, Arrays.fill will fill the all array with the given value, so that’s why you’re getting [23, 23, 23, 23, 23, 23, 23, 23]
.