简体   繁体   English

数组列表到数组数组

[英]List of arrays to array of arrays

I have a List of arrays of integers. 我有一个整数数组列表。 I want to convert it to an array of arrays of integers, but when using toArray() I get the error [Ljava.lang.Object; cannot be cast to [[I 我想将其转换为整数数组,但是使用toArray()出现错误[Ljava.lang.Object; cannot be cast to [[I [Ljava.lang.Object; cannot be cast to [[I

What am I doing wrong? 我究竟做错了什么? Thanks 谢谢

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

EDIT 编辑

I've seen that in this case I can convert it with: 我已经看到,在这种情况下,我可以将其转换为:

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

But only because all the integer arrays have the same size (2). 但这仅是因为所有整数数组都具有相同的大小(2)。 What If I don't know it? 如果我不知道该怎么办? Thanks 谢谢

You need to call 你需要打电话

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

Your old call cells.toArray() does not work since this creates an array of objects Object[] which apparently cannot be cast to int[][] 您的旧调用cells.toArray()无法正常工作,因为这会创建对象Object[]的数组,该对象显然无法转换为int[][]

Try to use something like this: 尝试使用如下形式:

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

Or use just: 或仅使用:

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

Instead of: 代替:

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

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

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