Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.setAll wont work with boolean

I want to create a big array, and want to try out some lambda, but for some reason that:

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

wont work, even that:

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

dose not work.

The compiler error is :

Type mismatch: cannot convert from boolean to T

and:

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

like image 524
TheSorm Avatar asked Sep 13 '17 13:09

TheSorm


1 Answers

Because it should be reference type: Boolean:

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

UPD: if you want to use boolean type, you have to write your own implementation of setAll() for 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: As @Holger mentioned, the name BooleanUnaryOperator is misleading, and it is better to use the existent class for this purpose - IntPredicate. (In this case change array[i] = generator.apply(i); to array[i] = generator.test(i);)

like image 142
Andremoniy Avatar answered Oct 14 '22 19:10

Andremoniy