Fill an Object Array using Index in Java
Declaration :
1 |
public static void fill(object[] a, int fromIndex, int toIndex, object val) |
Explanation :
Purpose | The java.util.Arrays.fill(object[] a int fromIndex int toIndex object val) method assigns the specified Object reference to each element of the specified range of the specified array of objects. The range to be filled extends from index fromIndex inclusive to index toIndex exclusive.(If fromIndex==toIndex the range to be filled is empty.). |
Parameters | a ===> This is the array to be filled. |
fromIndex ===> This is the index of the first element (inclusive) to be filled with the specified value. | |
toIndex ===> This is the index of the last element (exclusive) to be filled with the specified value. | |
val ===> This is the value to be stored in all elements of the array. | |
Return Value | This method does not return any value. |
Exception | ArrayIndexOutOfBoundsException — if fromIndex < 0 or toIndex > a.length ,IllegalArgumentException — if fromIndex > toIndex ,ArrayStoreException — if the specified value is not of a runtime type that can be stored in the specified array. |
Java Program : Example
Below example will explain java.util.Arrays.fill() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize an object array Object arr[] = new Object[] { 10.5, 20.5, 30.5, 40.5, 50.5 }; // Print the original array System.out.println("Original Array : "); for (Object val : arr) { System.out.println("Original element is " + val); } // Use fill to place 5.5 in the range index 0 to 3 Arrays.fill(arr, 0, 3, 5.5); // Print the new array System.out.println("\nNew Array is : "); for (Object val : arr) { System.out.println("New element is " + val); } } } |
Output of Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Original Array : Original element is 10.5 Original element is 20.5 Original element is 30.5 Original element is 40.5 Original element is 50.5 New Array is : New element is 5.5 New element is 5.5 New element is 5.5 New element is 40.5 New element is 50.5 |