當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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)

This method doesn't return any value.
Exceptions it Throws:
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)填充2D陣列

// 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)填充3D陣列

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



相關用法


注:本文由純淨天空篩選整理自 Arrays.fill() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。