简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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