Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill an array with descending values

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading