多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## Arrays的setAll方法 在Java 8中, 在**RaggedArray.java** 中引入并在 **ArrayOfGenerics.java.Array.setAll()** 中重用。它使用一个生成器并生成不同的值,可以选择基于数组的索引元素(通过访问当前索引,生成器可以读取数组值并对其进行修改)。 **static Arrays.setAll()** 的重载签名为: * **void setAll(int[] a, IntUnaryOperator gen)** * **void setAll(long[] a, IntToLongFunction gen)** * **void setAll(double[] a, IntToDoubleFunctiongen)** * **<T> void setAll(T[] a, IntFunction<? extendsT> gen)** 除了 **int** , **long** , **double** 有特殊的版本,其他的一切都由泛型版本处理。生成器不是 **Supplier** 因为它们不带参数,并且必须将 **int** 数组索引作为参数。 ```java // arrays/SimpleSetAll.java import java.util.*; import static onjava.ArrayShow.*; class Bob { final int id; Bob(int n) { id = n; } @Override public String toString() { return "Bob" + id; } } public class SimpleSetAll { public static final int SZ = 8; static int val = 1; static char[] chars = "abcdefghijklmnopqrstuvwxyz" .toCharArray(); static char getChar(int n) { return chars[n]; } public static void main(String[] args) { int[] ia = new int[SZ]; long[] la = new long[SZ]; double[] da = new double[SZ]; Arrays.setAll(ia, n -> n); // [1] Arrays.setAll(la, n -> n); Arrays.setAll(da, n -> n); show(ia); show(la); show(da); Arrays.setAll(ia, n -> val++); // [2] Arrays.setAll(la, n -> val++); Arrays.setAll(da, n -> val++); show(ia); show(la); show(da); Bob[] ba = new Bob[SZ]; Arrays.setAll(ba, Bob::new); // [3] show(ba); Character[] ca = new Character[SZ]; Arrays.setAll(ca, SimpleSetAll::getChar); // [4] show(ca); } } /* Output: [0, 1, 2, 3, 4, 5, 6, 7] [0, 1, 2, 3, 4, 5, 6, 7] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] [1, 2, 3, 4, 5, 6, 7, 8] [9, 10, 11, 12, 13, 14, 15, 16] [17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0] [Bob0, Bob1, Bob2, Bob3, Bob4, Bob5, Bob6, Bob7] [a, b, c, d, e, f, g, h] */ ``` * **[1]** 这里,我们只是将数组索引作为值插入数组。这将自动转化为 **long** 和 **double** 版本。 * **[2]** 这个函数只需要接受索引就能产生正确结果。这个,我们忽略索引值并且使用 **val** 生成结果。 * **[3]** 方法引用有效,因为 **Bob** 的构造器接收一个 **int** 参数。只要我们传递的函数接收一个 **int** 参数且能产生正确的结果,就认为它完成了工作。 * **[4]** 为了处理除了 **int** ,**long** ,**double** 之外的基元类型,请为基元创建包装类的数组。然后使用 **setAll()** 的泛型版本。请注意,**getChar()** 生成基元类型,因此这是自动装箱到 **Character** 。