【问题标题】:How to convert ArrayList<String[]> to multidimensional array String[][]?如何将 ArrayList<String[]> 转换为多维数组 String[][]?
【发布时间】:2021-05-17 13:49:17
【问题描述】:

我有一个 String[] 值的集合,例如:

ArrayList<String[]> values = new ArrayList<>();

String[] data1 = new String[]{"asd", "asdds", "ds"};
String[] data2 = new String[]{"dss", "21ss", "pp"};

values.add(data1);
values.add(data2);

我需要将其转换为多维数组 String[][]。 当我尝试这个时:

String[][] arr = (String[][])values.toArray();

我收到了ClassCastException

我该如何解决这个问题?

【问题讨论】:

    标签: java arraylist multidimensional-array collections classcastexception


    【解决方案1】:

    这个呢(这需要 Java 11 而toArray(String[][]::new) 需要)

    values.toArray(new String[0][0]);
    

    那个方法是:

    /**
     * Returns an array containing all of the elements in this list in proper
     * sequence (from first to last element); the runtime type of the returned
     * array is that of the specified array.  If the list fits in the
     * specified array, it is returned therein.  Otherwise, a new array is
     * allocated with the runtime type of the specified array and the size of
     * this list.
    

    【讨论】:

      【解决方案2】:

      不用不用投,查看the doc,可以直接使用:

      String[][] arr = values.toArray(new String[0][]);
      

      或者如果您使用的是Java 11

      String[][] arr = values.toArray(String[][]::new);
      

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 2012-06-23
        • 1970-01-01
        • 2011-08-20
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 2015-07-20
        • 2012-05-01
        相关资源
        最近更新 更多