gpt4 book ai didi

java - Arrays.setAll 不适用于 boolean 值

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:43 25 4
gpt4 key购买 nike

我想创建一个大数组,并想尝试一些 lambda,但出于某种原因:

cells = new boolean[this.collums][this.rows];
IntStream.range(0, cells.length).forEach(x -> Arrays.setAll(cells[x], e -> MathX.fastNextInt(1) == 0 ? true : false));

不会工作,即使那样:

cells = new boolean[this.collums][this.rows];
IntStream.range(0, cells.length).forEach(x -> Arrays.setAll(cells[x], e -> true));

剂量不起作用。

编译器错误是:

Type mismatch: cannot convert from boolean to T

和:

The method setAll(T[], IntFunction) in the type Arrays is not applicable for the arguments (boolean[], ( e) -> {})

最佳答案

因为应该是引用类型:Boolean:

Boolean[][] cells = new Boolean[this.collums][this.rows];

UPD:如果你想使用boolean类型,你必须为原始 boolean 类型编写你自己的setAll()实现:

interface BooleanUnaryOperator {
boolean apply(int x);
}

public static void setAll(boolean[] array, BooleanUnaryOperator generator) {
for (int i = 0; i < array.length; i++)
array[i] = generator.apply(i);
}

UPD-2:作为@Holger提到,名称 BooleanUnaryOperator 具有误导性,为此目的最好使用现有的类 - IntPredicate . (在这种情况下,将 array[i] = generator.apply(i); 更改为 array[i] = generator.test(i);)

关于java - Arrays.setAll 不适用于 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com