Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to fill an array with values

Short answer

Arrays.fill() writes one value into every cell:

void main() {
    int[] scores = new int[5];
    Arrays.fill(scores, 10);
 
    IO.println(Arrays.toString(scores));
}

Output:

[10, 10, 10, 10, 10]

Default values

A new array is already filled: numbers with zeros, boolean with false, objects with null:

void main() {
    IO.println(Arrays.toString(new int[3]));
    IO.println(Arrays.toString(new boolean[2]));
    IO.println(Arrays.toString(new String[2]));
}

Output:

[0, 0, 0]
[false, false]
[null, null]

By a formula

Arrays.setAll() calculates each cell's value from its index:

void main() {
    int[] squares = new int[6];
    Arrays.setAll(squares, i -> i * i);
 
    IO.println(Arrays.toString(squares));
}

Output:

[0, 1, 4, 9, 16, 25]

A range of numbers

An array of consecutive numbers is easiest to get from an IntStream:

void main() {
    int[] range = IntStream.rangeClosed(1, 10).toArray();
    IO.println(Arrays.toString(range));
}

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Common mistake

Filling an array with a single mutable object. All cells point to the same object:

void main() {
    StringBuilder[] lines = new StringBuilder[3];
    Arrays.fill(lines, new StringBuilder());
    lines[0].append("Anna");
 
    IO.println(Arrays.toString(lines));
}

Output:

[Anna, Anna, Anna]

Create a separate object for each cell: Arrays.setAll(lines, i -> new StringBuilder()).

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.