To preset an array in Java, you can use the Arrays.fill
method of the java.util
package or the Arrays.setAll
method of the java.util.stream
package.
Here is an example of how you can use the Arrays.fill
method to preset an array in Java:
import java.util.Arrays; public class ArrayPreset { public static void main(String[] args) { int[] array = new int[10]; Arrays.fill(array, 5); System.out.println(Arrays.toString(array)); // [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] } }
In this example, the main
method creates an integer array with 10 elements and uses the Arrays.fill
method to preset all the elements with the value 5
. The Arrays.fill
method takes the array and the value as arguments and sets all the elements of the array to the specified value.
Here is an example of how you can use the Arrays.setAll
method to preset an array in Java:
import java.util.Arrays; import java.util.function.IntUnaryOperator; public class ArrayPreset { public static void main(String[] args) { int[] array = new int[10]; Arrays.setAll(array, i -> i * 2); System.out.println(Arrays.toString(array)); // [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] } }
In this example, the main
method creates an integer array with 10 elements and uses the Arrays.setAll
method to preset all the elements with a function. The Arrays.setAll
method takes the array and a IntUnaryOperator
function as arguments and sets all the elements of the array to the result of the function.
The IntUnaryOperator
function takes an integer index as an argument and returns a value, which is used to preset the corresponding element of the array. In this example, the function multiplies the index by 2, so the elements of the array are set to 0, 2, 4, 6, 8, 10, 12, 14, 16, and 18.
Keep in mind that these are just two examples of how you can preset an array in Java. You can use different techniques and functions to achieve the same result, such as using a loop to set the elements of the array or using the java.util.stream
package to generate a stream of values.