0

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?

0

3 Answers 3

3

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

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

1
  • 2
    A 2-d array is a 1-d array of 1-d arrays. If you provide a 1-d array as the second argument of the fill method, it would work. And that's the problem here.
    – Rahul
    Commented Feb 5, 2014 at 10:48
2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.