0

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

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

1
  • How are you storing the return value of this function ? Commented Jan 27, 2016 at 13:22

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.