In Java, Arrays.fill(a, val) stores val in every element of the array a. Arrays.fill(a, from, to, val) does the same for indexes from up to, but not including, to.
New arrays start with default values (0, false, or null). fill is the quick way to start with something else, such as -1 for "not set yet", or to reset an array you are reusing. It changes the array in place and returns nothing.
A static method of java.util.Arrays (Java 1.2+): call it on the class, as in Arrays.fill(...); there is no Arrays object to create.
Syntax
Fill everything, or give a range first.
Java
int[] a = new int[5];
Arrays.fill(a, 7); // [7, 7, 7, 7, 7]
Arrays.fill(a, 1, 3, 0); // [7, 0, 0, 7, 7]
String[] s = new String[3];
Arrays.fill(s, "?"); // [?, ?, ?]
Call
What it does
Arrays.fill(a, val)
Every element becomes val.
Arrays.fill(a, from, to, val)
Only indexes from to to - 1 change.
Arrays.fill(chars, ' ')
Blank out a char[] buffer.
for (int[] row : grid) Arrays.fill(row, v)
Fill a 2D array one row at a time.
Both forms exist for long[], int[], short[], char[], byte[], boolean[], float[], double[], and Object[]: eighteen overloads in total.
Library declarations
Java
// java.util.Arrays (since Java 1.2)
public static void fill(int[] a, int val)
public static void fill(int[] a, int fromIndex, int toIndex, int val)
public static void fill(boolean[] a, boolean val)
public static void fill(Object[] a, Object val)
public static void fill(Object[] a, int fromIndex, int toIndex, Object val)
// same pair for long[], short[], char[], byte[], float[], double[], boolean[]
Parameters
Parameter
Description
a
The array to fill. Must not be null.
fromIndex, toIndex (optional)
Range to fill: fromIndex inclusive, toIndex exclusive.
One row object.new int[2] runs once, and fill(Object[], Object) stores that same reference in all three slots of wrong.
One change, three rows. Setting wrong[0][0] = 9 changes the shared row, so every row appears to start with 9.
Separate rows.new int[3][2] creates three independent rows, and the loop fills each one with 7.
Only the first row changes. In right, the 9 appears in row 0 only, which is usually what you want.
Frequently Asked Questions
Create the array, then call Arrays.fill(array, value). For example, int[] a = new int[10]; Arrays.fill(a, -1);
Yes. Arrays.fill(a, from, to, value) fills indexes from to to - 1.
Loop over the rows and call Arrays.fill(row, value) on each. Calling Arrays.fill(grid, new int[n]) puts the same row object in every slot.
No. It returns void and changes the array you pass in.
NullPointerException for a null array, IllegalArgumentException or ArrayIndexOutOfBoundsException for a bad range, and ArrayStoreException when an Object[] cannot hold the value.