4

I have a problem with the following example:

public static void main(String[] args) {

    // this works
    int[] test1DArray = returnArray();

    int[][] test2DArray = new int[][] {

        // this does not work
        new int[]= returnArray(),

        // yet this does
        new int[] {1, 2 ,3}
}

private static int[] returnArray() {

    int[] a = {1, 2, 3};
    return a;
}

I am looking for a way to create a two-dimensional array, and have the second dimension be the array that is returned from a method. I do not understand why it does not work, as the error I am getting in Eclipse is

The left-hand side of an assignment must be a variable

From my understanding, I am creating a new int array and assigning the returned value to it. Populating the second dimension array immediately like this

new int[] {1, 2 ,3}

works like a charm, and I am looking to do something similar with the array that's returned to me from returnArray()

Any help is greatly appreciated.

p/

2 Answers 2

4

Just use:

int[][] test2DArray = new int[][] {
    returnArray(),
    new int[] {1,2 ,3}
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just what I was looking for!
2

Although @Eran has solved the problem, I feel you should understand why this went wrong.

When you initialize the contents of an array, you are basically returning values to it.

E.g.: new int[]{1, 2, 3} returns 1, 2, and 3 inside test2Darray, whereas int[] n = new int[]{1, 2, 3} is initializing and declaring an array inside test2Darray. The latter is not returning any primitive value inside the array, so it gives an error.

returnValue() is a method which does return a value (an integer array). So the control considers it equivalent to typing new int[]{1, 2, 3}.

Hence new int[]{1, 2, 3} and returnValue() work.

1 Comment

Thanks for the background, really helps to understand where I went wrong!

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.