填充替换数组元素
类 | 方法(静态) |
---|---|
Arrays | fill() |
作用:对数组中的元素进行替换和填充
参数类型 | 作用 |
---|---|
fill(int[] a,int value) | a:要进行元素替换的数组
Value:要存储数组中所有元素的值 |
fill(int[] a,int fromIndex,int toIndex,int value) | a:要进行填充的数组
fromIndex:要使用指定值填充的第一个元素的索引(包括)注:指数组下标 toIndex:要使用指定值填充的最后一个元素的索引(不包括)注:指数组下标 value:要存储在数组所有元素中的值 |
代码如下:
//fill方法的使用
import java.util.Arrays;//导入类
public class Swap {
public static void main(String[] args) {
int[] arr = new int[5];
Arrays.fill(arr, 6);//使用一个值对数组进行填充
for(int i = 0; i < arr.length; i++) {//循环遍历数组中的元素
System.out.println("第" + (i + 1) + "个元素是" + arr[i]);
/*
结果为:
第1个元素是6
第2个元素是6
第3个元素是6
第4个元素是6
第5个元素是6
*/
}
}
}
import java.util.Arrays;//导入类
public class Swap {
public static void main(String[] args) {
int[] arr = new int[] {1,2,3,4};
Arrays.fill(arr,1,2,5);
for(int x : arr) {
System.out.print(x + " ");//结果为1,5,3,4
}
}
}
注意事项:指定的索引位置不能大于或者等于填充数组的长度,则会报出ArrayIndexOutOfBoundsException(数组越界异常)