I want to add a multidimensional Boolean Array to an ArrayList. How do I do that?
Below is an simple example:
public boolean[][] BooleanArray; ArrayList<Boolean[][]> BooleanArrayList= new ArrayList<Boolean[][]>(); public void AddBooleanArrayToList(){ BooleanArrayList.add(BooleanArray); }
However this example does not work. This error will prompt:
The method add(Boolean[][]) in the type ArrayList<Boolean[][]> is not applicable for the arguments (boolean[][])
Advertisement
Answer
The problem here is that you defined the ArrayList to take 2D arrays of the wrapper class Boolean
, but you are trying to add a 2D array of the primitive type boolean
. Those are not the same type, hence the error. You are able to get away with this when you aren’t storing arrays thanks to a nice little Java feature called auto-boxing, which converts between Boolean
and boolean
automatically, but auto-boxing isn’t smart enough to work on arrays. The fix is simple; just capitalize the B in “boolean” in the declaration for BooleanArray
. It should look like so:
public Boolean[][] BooleanArray;
Alternatively, (not recommended) you could manually box your array when you want to add it to the ArrayList like so:
BooleanArrayList.add( IntStream.range(0, BooleanArray.length) .mapToObj((i) -> IntStream.range(0, BooleanArray[i].length) .mapToObj((j) -> BooleanArray[i][j]) .toArray(Boolean[]::new)) .toArray(Boolean[][]::new));