Arrays setAll Generator Initialization
Arrays.setAll fills an array from an index-based generator, and parallelSetAll splits the same job across threads when the fill is expensive.
Code
import java.util.Arrays;
public class ArrayFill {
public static void main(String[] args) {
int[] squares = new int[8];
// setAll:生成器收下标,返回该位置的元素值
Arrays.setAll(squares, i -> i * i);
System.out.println("squares: " + Arrays.toString(squares));
// 索引感知的初始化:斐波那契前八项
long[] fib = new long[8];
Arrays.setAll(fib, i -> i < 2 ? i : fib[i - 1] + fib[i - 2]);
System.out.println("fib: " + Arrays.toString(fib));
// 对象数组同样适用:按下标生成标签
String[] labels = new String[3];
Arrays.setAll(labels, i -> "node-" + (char) ('a' + i));
System.out.println("labels: " + Arrays.toString(labels));
// parallelSetAll:同一生成器并行填充(生成器须无副作用)
long[] big = new long[64];
Arrays.parallelSetAll(big, i -> (long) i * (i + 1) / 2);
System.out.println("tri[63]: " + big[63]);
}
}How it works
Arrays setAll Generator Initialization comes down to the class ArrayFill and the function main.
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
The signature you will reach for first is public static void main(String[] args)
The output comes back labeled — squares:, fib:, labels: — when the file runs.
Key statements worth quoting
Arrays.setAll(fib, i -> i < 2 ? i : fib[i - 1] + fib[i - 2]);
Arrays.parallelSetAll(big, i -> (long) i * (i + 1) / 2);
Arrays.setAll(labels, i -> "node-" + (char) ('a' + i));
Interactive Tools for This Topic
FAQ
- What does Arrays setAll Generator Initialization print when run?
- Invoke the file as-is — the `squares:`, `fib:`, `labels:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.