0

For a certain API [1], arrays of data have to be passed as elements of a Java Object array (one such element per array). The following works fine, and the 2D double array AInData is accepted by the API as the 1st argument (and there is only 1 argument):

double[][] AInData = {{1.1, 1.2, 1.3}, {2.1, 2.2, 2.3}};
Object[] arObj = { AInData };

Since floating point literals default to double, I thought I could do without the intermediate variable AInData:

Object[] arObj = { {{1.1, 1.2, 1.3}, {2.1, 2.2, 2.3}} };

This caused the following errors:

illegal initializer for Object
Object[] arObj = { {{1.1, 1.2, 1.3}, {2.1, 2.2, 2.3}} };
                   ^
illegal initializer for <none>
Object[] arObj = { {{1.1, 1.2, 1.3}, {2.1, 2.2, 2.3}} };
                    ^
illegal initializer for <none>
Object[] arObj = { {{1.1, 1.2, 1.3}, {2.1, 2.2, 2.3}} };
                                     ^

Why can I not do away with AInData?

If literals truly default to double, then there is no casting when AInData is initialized.

NOTES:

[1] Interface to Matlab

1 Answer 1

1

Actually, you can

Object [] arObj = new double [][][] {{{1.1, 1.2, 1.3}, {2.1, 2.2, 2.3}} };
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks....can you please explain what is happening in my original code from a semantic perspective? I thought that an literal array of anything is delineated by curly braces, with array elements separated by commas. By that logic, the literal 2D double array should have become the first (and only) Object element in the array. I don't understand why it's necessary to created a 3D double array.
Furthermore, it seems that the compiler disassembles the 3D array along the 3rd dimension and takes each resulting 2D array (of which there is only one) as the elements of the Object array. I've not seen this behaviour described anywhere, which makes me question question whether I understand what is happenging in your code (or perhaps I'm missing a designed-for behaviour of Java when assigning arrays to arrays).
@user36800 In Java multidimensional array is just an array of arrays. Each array, also, is an object. So is acceptable to cast any dimensional array of anything to an object array.
@user36800 No, I guess it's initialization convention. Need to find proof in JLS. My guess is: Object[][] acceptable = {{},{}}; Object[] not_acceptable = {{},{}}; And RHS doesn't depend on type
|

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.