Arrays.setAll will not work with boolean

I want to create a large array and try trying lambda, but for some reason:

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));

does not work even if:

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

the dose does not work.

Compiler Error:

Type mismatch: cannot convert from Boolean to T

and

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

+4
source share
2 answers

Because it must be a reference type Boolean::

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

UPD: if you want to use a type Boolean, you need to write your own implementation setAll()for a primitive boolean type:

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);)

+8

true Arrays.fill :

cells = new boolean[this.collums][this.rows];
for (boolean[] cell : cells) {
    Arrays.fill(cell, true);
}

, setAll , Boolean :

Boolean [][] cells = new Boolean[10][10];
IntStream.range(0, cells.length).forEach(x -> Arrays.setAll(cells[x], e -> true));

Arrays setAll boolean[], setAll(T[] array,IntFunction<? extends T> generator), . , setAll, Boolean, @Andremoniy.

+1

Source: https://habr.com/ru/post/1685598/


All Articles