Arrays.fill
时间: 2023-12-09 15:04:14 浏览: 35
Arrays.fill is a method in Java that is used to fill an array with a specific value. It is a convenient way to initialize an array to a specific value or reset the contents of an array to a default value.
The method takes three arguments: the array to be filled, the starting index from which to fill the array, and the ending index up to which the array should be filled. The syntax for the method is as follows:
Arrays.fill(array, startIndex, endIndex, value);
The startIndex is the index at which to start filling the array and the endIndex is the index up to which the array should be filled. The value parameter specifies the value with which to fill the array.
Here's an example of using the Arrays.fill method to initialize an array with a specific value:
int[] myArray = new int[5];
Arrays.fill(myArray, 0, 5, 10);
This code creates a new int array with 5 elements, and then fills it with the value 10 starting from index 0 and ending at index 4.
Note that if the startIndex is greater than or equal to the endIndex, the method will not modify the array. Also, if the endIndex is greater than the length of the array, an ArrayIndexOutOfBoundsException will be thrown.