繁体   English   中英

数组列表到数组数组

[英]List of arrays to array of arrays

我有一个整数数组列表。 我想将其转换为整数数组,但是使用toArray()出现错误[Ljava.lang.Object; cannot be cast to [[I [Ljava.lang.Object; cannot be cast to [[I

我究竟做错了什么? 谢谢

public int[][] getCells() {
    List<int[]> cells = new ArrayList<>();

    for (int y = this.y0; y <= this.y1 ; y++) {
        for (int x = this.x0; x <= this.x1 ; x++) {
            cells.add(new int[]{x, y});
        }
    }

    return (int[][]) cells.toArray();
}

编辑

我已经看到,在这种情况下,我可以将其转换为:

return cells.toArray(new int[cells.size()][2]);

但这仅是因为所有整数数组都具有相同的大小(2)。 如果我不知道该怎么办? 谢谢

你需要打电话

cells.toArray(new int[cells.size()][])

您的旧调用cells.toArray()无法正常工作,因为这会创建对象Object[]的数组,该对象显然无法转换为int[][]

尝试使用如下形式:

    return (int[][])cells.toArray(new int[cells.size()][]);

或仅使用:

    return cells.toArray(new int[][]{});

代替:

    return (int[][]) cells.toArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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