Populating the entire array with same element

In this post under Java Collections, I will show with example an api provided in “Arrays” class that will populate any array with a particular element.

We are talking about “Arrays” class static method “fill”. It takes two arguments
1) the array to be populated
2) the element to be fill int array

For our example I will use an integer array and fill it completely with a same number.

Below is the complete main class for your reference

Main class

package core.collection;
  
import java.util.Arrays;
  
public class ArraysFillDemo {
      public static void main(String[] args) {
          int[] integerList = new int[10];
          String result = Arrays.toString(integerList);
          System.out.println("Before modification: " + result);
         Arrays.fill(integerList, 1);
         result = Arrays.toString(integerList);
         System.out.println("After modification: " + result);
     }
}

In the above code, at line 7, I create an integer array of size 10.

At line 10, I am calling “Arrays” class static method “fill” passing the integer array and element to be inserted (i.e., in this case 1) as arguments.

As a result of the call at line 10, all the 10 slots of the array “integerList” are set to 1.

There are other overloaded versions of “fill” method. Please refer to javadoc for more info.

In this way we can use “fill” static method.

Leave a comment