Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Arrays.setAll in Java?

abhilash

The setAll method in the Arrays class is used to set all the elements in an array specified by the generator function. Arrays is defined in the util package in Java, so you must import the util package before using the setAll function. This is shown below:

import java.util.Arrays;

Method signature

public static void setAll(int[] array, IntUnaryOperator generator) 

Parameters

  • int[] array: The array to be initialized.
  • IntUnaryOperator generator: A function that accepts an index and producse the desired value for that position

Overloaded methods

  • setAll(T[] array, IntFunction<? extends T> generator)
  • setAll(int[] array, IntUnaryOperator generator)
  • setAll(long[] array, IntToLongFunction generator)
  • setAll(double[] array, IntToDoubleFunction generator)

Code

In the following code, we define an integer array and a generator function that adds five to the index of every element in the array. Next, we pass the array and the generator function to the Arrays.setAll method to set the elements of the array:

import java.util.Arrays;
import java.util.function.IntUnaryOperator;

public class Main {

    public static void main(String[] args) {
        int array[] = new int[5];
        IntUnaryOperator generatorFunction = operand -> operand * 5;
        Arrays.setAll(array, generatorFunction);
        for(int num:array) System.out.print(num+" ");
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring