Arrays.fill() w Javie z przykładami

java.util.Arrays.fill() metoda jest włączona Klasa java.util.Arrays . Ta metoda przypisuje określoną wartość typu danych do każdego elementu określonego zakresu określonej tablicy.

 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. 
 Exceptions it Throws: IllegalArgumentException - if from_Index>to_Index ArrayIndexOutOfBoundsException - jeśli from_Index a.length 

Przykłady:

Możemy wypełnić całą tablicę.




// Java program to fill a subarray of given array> import> java.util.Arrays;> > public> class> Main> {> > 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(> 'Array completely filled'> +> > ' with 10 '> + Arrays.toString(ar));> > }> }>

Wyjście:

Array completely filled with 10 [10, 10, 10, 10, 10, 10, 10, 10, 10] 

Możemy wypełnić część tablicy.




// Java program to fill a subarray array with> // given value.> import> java.util.Arrays;> > public> class> Main> {> > public> static> void> main(String[] args)> > {> > int> ar[] = {> 2> ,> 2> ,> 2> ,> 2> ,> 2> ,> 2> ,> 2> ,> 2> ,> 2> };> > > // Fill from index 1 to index 4.> > Arrays.fill(ar,> 1> ,> 5> ,> 10> );> > > System.out.println(Arrays.toString(ar));> > }> }>

Wyjście:

[2, 10, 10, 10, 10, 2, 2, 2, 2] 

Możemy wypełnić tablicę wielowymiarową
Możemy użyć pętli do wypełnienia tablicy wielowymiarowej.
1) Wypełnij tablicę 2D




// Java program to fill a multidimensional array with> // given value.> import> java.util.Arrays;> > public> class> Main> {> > 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));> > }> }>

Wyjście:

[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]] 

2) Wypełnij tablicę 3D




// Java program to fill a multidimensional array with> // given value.> > import> java.util.Arrays;> > class> GFG {> > > public> static> void> main(String[] args) {> > int> [][][] ar => new> int> [> 3> ][> 4> ][> 5> ];> > > // Fill each row with -1.> > for> (> int> [][] row : ar) {> > for> (> int> [] rowColumn : row) {> > Arrays.fill(rowColumn, -> 1> );> > }> > }> > > System.out.println(Arrays.deepToString(ar));> > }> }>

Wyjście:

[[[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]], [[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]], [[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]]]