java.util.Arrays.fill()方法用于将指定的int值赋给指定的每个元素指定整数数组的范围。
语法
public static void fill(int[] a, int fromIndex, int toIndex, int val)
参数
a | 指定要填充的数组。 |
fromIndex | 指定第一个元素(含)的索引 |
toIndex | 指定要填充的最后一个元素(不包括)的索引指定的值。 |
val | 指定要存储在数组所有元素中的值。 |
返回值
void类型。
异常
- 抛出IllegalArgumentException ,如果 fromIndex > toIndex。
- 抛出 ArrayIndexOutOfBoundsException,如果 fromIndex < 0 或 toIndex > a.length。
示例:
在下面的示例中,java.util.Arrays.fill() 方法用于使用给定 int 数组的指定范围填充指定的 int 值。
import java.util.*;
public class MyClass {
public static void main(String[] args) {
//创建一个int数组
int MyArr[] = {10, 2, -3, 35, 56};
//打印数组
System.out.print("MyArr contains:");
for(int i: MyArr)
System.out.print(" " + i);
//填充数组的指定范围
//有5个int值
Arrays.fill(MyArr, 1, 4, 5);
//打印数组
System.out.print("\nMyArr contains:");
for(int i: MyArr)
System.out.print(" " + i);
}
}
上述代码的输出将是:
MyArr contains: 10 2 -3 35 56
MyArr contains: 10 5 5 5 56