Java.util.Arrays.fill() 方法

描述

java.util.Arrays.fill(byte[] a, int fromIndex, int toIndex, byte val) 方法将指定的字节值分配给指定字节数组的指定范围的每个元素。 要填充的范围从索引fromIndex(含)到索引toIndex(不含)。(如果fromIndex==toIndex,则要填充的范围为空。)


声明

以下是 java.util.Arrays.fill() 方法的声明

public static void fill(byte[] a, int fromIndex, int toIndex, byte val)

参数

  • a − 这是要填充的数组。

  • fromIndex − 这是要填充指定值的第一个元素(包括)的索引。

  • toIndex − 这是要填充指定值的最后一个元素(不包括)的索引。

  • val − 这是要存储在数组所有元素中的值。


返回值

此方法不返回任何值。


异常

  • ArrayIndexOutOfBoundsException − 如果 fromIndex < 0 或 toIndex > a.length

  • IllegalArgumentException − 如果 fromIndex > toIndex


示例

下面的例子展示了 java.util.Arrays.fill() 方法的使用。

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {

      // initializing byte array
      byte arr[] = new byte[] {1, 6, 3, 2, 9};

      // let us print the values
      System.out.println("Actual values: ");
      for (byte value : arr) {
         System.out.println("Value = " + value);
      }

      // using fill for placing 64 from index 2 to 4
      // converting int to byte
      Arrays.fill(arr, 2, 4, (byte)64);

      // let us print the values
      System.out.println("New values after using fill() method: ");
      for (byte value : arr) {
         System.out.println("Value = " + value);
      }
   }
} 

让我们编译并运行上面的程序,这将产生以下结果 −

Actual values:
Value = 1
Value = 6
Value = 3
Value = 2
Value = 9
New values after using fill() method:
Value = 1
Value = 6
Value = 64
Value = 64
Value = 9