1. Difinition
java.util.Arrays.fill() method is in java.util.Arrays class.
This method assigns the specified data type value to each element of the specified range of the specified
array.
2.Fill entire array.
Syntax:
// Makes all elements of a[] equal to "val"
public static void fill(int[] a, int val)
// Makes elements from from_Index (inclusive) to to_Index
// (exclusive) equal to "val"
public static void fill(int[] a, int from_Index, int to_Index, int val)
This method doesn't return any value.
public class A{
public static void main(String[] args) {
int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
// To fill complete array with a particular
// value
Arrays.fill(ar, 10);
System.out.println(Arrays.toString(ar));
}
}
[10, 10, 10, 10, 10, 10, 10, 10, 10]
3.Fill part of array.
public class A{
public static void main(String[] args) {
int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
// Fill from index 1 to index 4.
Arrays.fill(ar, 1, 5, 10);
System.out.println(Arrays.toString(ar));
}
}
[2, 10, 10, 10, 10, 2, 2, 4, 2]
4.Fill a multidimensional array
Using a loop to fill a multidimensional array.
4.1 Fill 2D Array
public class A{
public static void main(String[] args) {
int [][]ar = new int [3][4];
// Fill each row with 10.
for (int[] row : ar)
Arrays.fill(row, 10);
System.out.println(Arrays.deepToString(ar));
}
}
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]
Note:
Arrays.deepToString()Syntax:
public static String deepToString(Object[] arr)
arr - An array whose string representation is needed
This function returns string representation of arr[].
It returns “null” if the specified array is null.This method is designed for converting multidimensional arrays to strings. The simple toString() method works well for simple arrays, but doesn’t work for multidimensional arrays. This method is designed for converting multi-dimensional arrays to strings.
public class A{
public static void main(String[] args) {
// Create a 2D array
int[][] mat = new int[2][2];
mat[0][0] = 99;
mat[0][1] = 151;
mat[1][0] = 30;
mat[1][1] = 5;
// print 2D integer array using deepToString()
System.out.println(Arrays.deepToString(mat));
}
}
[[99, 151], [30, 5]]
4.2 Fill 3D Array
public class A{
public static void main(String[] args) {
int[][][] ar = new int[2][3][4];
// Fill each row with 1.
for (int[][] row : ar) {
for (int[] rowColumn : row) {
Arrays.fill(rowColumn, 1);
}
}
System.out.println(Arrays.deepToString(ar));
}
}
[[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]