简体   繁体   中英

Java cannot create simple 2d boolean array

Running the code:

    public static boolean[][] makeright(boolean tf, BufferedImage in){
        boolean[][] ret = new boolean[in.getWidth()][in.getHeight()];
        Arrays.fill(ret, tf);
        return ret;
    }

gave me a

java.lang.ArrayStoreException: java.lang.Boolean
    at java.util.Arrays.fill(Arrays.java:2697)
    at neuro.helper.makeright(helper.java:35)
    at neuro.helper.main(helper.java:20)

exception, line 35 is the line where I create the boolean[][] ret. Does anybody know what a ArrayStoreException is and how I can prevent it?

There is no version of Arrays.fill that accepts a boolean[][] as parameter. See the docs here .

Or course, as RJ pointed out in the comments, you can pass a boolean[][] as first parameter as long as you pass a boolean[] as the second parameter.

The problem is that you're trying to using Arrays.fill() on a 2 dimensional array instead of a 1 dimensional. You can solve this by looping over the separate (1 dimensional) arrays in your 2D array.

public class Test {
    public static void main(String[] args){
        boolean[][] ret = new boolean[5][5];
        for(boolean[] arr : ret){
            Arrays.fill(arr, true);
        }

        for(boolean[] arr : ret){
            System.out.println(Arrays.toString(arr));
        }
    }
}

This will output

[true, true, true, true, true]
[true, true, true, true, true]
[true, true, true, true, true]
[true, true, true, true, true]
[true, true, true, true, true]

See the ArrayStoreException :

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

And Arrays.fill(boolean[] a, boolean val) :

Assigns the specified boolean value to each element of the specified array of booleans .

You can also use the more general public static void fill(Object[] a, Object val) to pass in an array of boolean values like this:

public static void main(String[] args) {
    boolean[][] ret = new boolean[5][5];
    boolean[] tofill = new boolean[] { true, true, true, true, true };

    Arrays.fill(ret, tofill);

    for (boolean[] arr : ret) {
        System.out.println(Arrays.toString(arr));
    }
}

You are trying to fill an array of Boolean arrays with single boolean values which will not work. Instead you will have to do something like this:

for (int i = 0; i < ret.length; i++) {
   Arrays.fill(ret[i], tf);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM