Java uses the fill() function of the Arrays class to fill all elements of the two-dimensional array with the specified value
In Java programming, arrays are a very common data structure, and two-dimensional arrays are even more popular in Java programming. A data structure often used when working with multidimensional data. When we need to fill all elements of a two-dimensional array with specified values, we can use the fill() function in Java's Arrays class to quickly achieve this.
The fill() function is a static method in the Arrays class, which can fill all elements of the array with specified element values. This method has three overloaded versions:
However, for two-dimensional arrays, the fill() function can only fill one-dimensional arrays and cannot be used directly to fill the entire two-dimensional array. Therefore, we need to combine loops to implement the filling operation of the two-dimensional array.
The following is a sample code that uses the fill() function to fill all elements of a two-dimensional array with specified values:
import java.util.Arrays; public class Main { public static void main(String[] args) { int[][] matrix = new int[3][3]; // 创建一个3x3的二维数组 int fillValue = 10; // 指定要填充的值 for (int[] row : matrix) { Arrays.fill(row, fillValue); // 逐行填充指定值 } // 打印二维数组 for (int[] row : matrix) { for (int num : row) { System.out.print(num + " "); } System.out.println(); // 换行 } } }
In the above code, we first create a 3x3 two-dimensional Arraymatrix
. Then, we specify the value to be filled as fillValue = 10
. Next, we use an enhanced for loop to iterate through each row of the two-dimensional array and fill the specified value into all elements of each row through the Arrays.fill()
function. Finally, we verify the results of the fill operation by printing all elements of the 2D array using a nested loop.
Run the above code, the output result is as follows:
10 10 10 10 10 10 10 10 10
As you can see, all elements of the two-dimensional array matrix
are successfully filled to the specified value of 10.
By using the fill() function of the Arrays class combined with a loop, we can efficiently fill all elements of a two-dimensional array. This can greatly simplify the writing of code and improve programming efficiency, making the code clearer and easier to read.
The above is the detailed content of Java uses the fill() function of the Arrays class to fill all elements of a two-dimensional array with specified values.. For more information, please follow other related articles on the PHP Chinese website!