java - Arrays.setAll 不适用于 boolean 值

标签 java arrays lambda java-8 boolean

我想创建一个大数组,并想尝试一些 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/

相关文章:

c++ - 来自 lambda 返回类型的模板化函数返回类型

java - 如何创建包含客户端证书链的 BKS (BouncyCaSTLe) 格式的 Java keystore

java - JFreeChart 中的 ohlc 图表

java - 如何使用分页和 spring data jpa 获取 findAll() 服务的所有记录?

c++ - 将一个数组的引用分配给另一个数组 - "warning: target of assignment not really an lvalue"

compiler-construction - 为 CLR 实现函数式语言(或者,关于 F# 实现的论文)

python 3 : how do I run a function over a list of lists of possible parameters and returning a dictionary of all results

java - 我如何在方法中使用 (WebElement webdriverWait Until element is clickable) 并调用该方法以供重新使用

c - 字符串段错误问题

字符串元素数组上的Javascript映射方法