【问题标题】:Java cannot create simple 2d boolean arrayJava 无法创建简单的二维布尔数组
【发布时间】:2014-02-05 10:43:17
【问题描述】:

运行代码:

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

给我一​​个

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)

例外,第 35 行是我创建 boolean[][] ret 的行。 有谁知道 ArrayStoreException 是什么以及如何防止它?

【问题讨论】:

    标签: java arrays exception multidimensional-array


    【解决方案1】:

    没有接受boolean[][] 作为参数的Arrays.fill 版本。请参阅文档here

    当然,如 R.J.在 cmets 中指出,只要将 boolean[] 作为第二个参数传递,就可以将 boolean[][] 作为第一个参数传递。

    【讨论】:

    • 二维数组是一维数组的一维数组。如果您提供一维数组作为fill 方法的第二个参数,它会起作用。这就是问题所在。
    【解决方案2】:

    问题是您试图在二维数组而不是一维数组上使用Arrays.fill()。您可以通过遍历二维数组中的单独(一维)数组来解决此问题。

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

    这将输出

    [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]
    

    ArrayStoreException

    抛出表示试图将错误类型的对象存储到对象数组中。

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

    将指定的布尔值分配给指定的布尔数组的每个元素。

    您还可以使用更通用的public static void fill(Object[] a, Object val) 来传递一个布尔值数组,如下所示:

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

    【讨论】:

      【解决方案3】:

      您正在尝试用单个布尔值填充布尔数组的数组,但这是行不通的。相反,您将不得不这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-09
        • 1970-01-01
        • 2020-01-04
        • 2014-07-29
        • 2022-01-23
        • 2012-08-27
        • 2017-02-20
        相关资源
        最近更新 更多