Java Arrays.fill()方法及示例

Java Arrays.fill()方法及示例

java.util.Arrays.fill() 方法是在java.util.Arrays类中。该方法将指定的数据类型值分配给指定数组的指定范围内的每个元素。

语法:

// 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)

这个方法不返回任何值
抛出的异常情况:

IllegalArgumentException - if from_Index > to_Index
ArrayIndexOutOfBoundsException - if from_Index  a.length

例子

我们可以填充整个数组

// 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\n" + Arrays.toString(ar));
    }
}

输出

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

我们可以填补数组的一部分

// 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));
    }
}

输出

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

我们可以填充一个多维数组
我们可以用一个循环来填充一个多维数组。

1)填充二维数组

// 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));
    }
}

输出

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

2) 填充三维数组

// 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));
    }
}

输出

[[[-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]]]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程