2

May be I am using 3D arrays first time. I just try to follow the 1D and 2D syntax to declare 3D, but compiler says Type mismatch. Can anyone tell me the reason behind this?

Integer[] _1D = new Integer[]{2,4,6,5,6};
Integer[][] _2D = new Integer[][]{{2,3},{4,6},{5,6}};
Integer[][][] _3D = new Integer[][][]{{1,2,3},{4,5,6},{7,8,9},{2,4,5}};

Thanks,

4 Answers 4

3

You're just creating a 2-d array again, but with 4 rows and 3 columns. This is the right way to create a 3-d array.

Integer[][][] _3D = new Integer[][][]{{{1,2,3},{4,5,6},{7,8,9},{2,4,5}},{{1,2,3},{4,5,6},{7,8,9},{2,4,5}}}; // it should be like this.
Sign up to request clarification or add additional context in comments.

1 Comment

I was bit confussed, but tried Integer[][][] _3D = new Integer[][][]{{1,2,3},{4,5,6},{7,8,9}}; this also.
2

Your 3d array is actually a 2d array. Add a brace pair to make it 3d.

Integer[][][] _3D = new Integer[][][]{{ {1,2,3},{4,5,6},{7,8,9} }};

Comments

2
{{1,2,3},{4,5,6},{7,8,9},{2,4,5}};

This is just a 2D array. An example of 3D array is:

Integer[][][] _3D = new Integer[][][]{{{1,2,3},{4,5,6}},{{7,8,9},{2,4,5}}};

A 3D array is an array that contains arrays that them contain arrays, so you can see with that premise that the first array only is an array that has arrays with numbers.

Comments

1

Adding on to @R.J 's answer, it's easier to see the three dimension like this

Integer[][][] _3D = 
             new Integer[][][]{  // dimension 1
                                 {   // dimension 2
                                    {1,2,3},  // dimension 3
                                    {4,5,6},
                                    {7,8,9},
                                    {2,4,5}
                                 },
                                 {  // dimension 2
                                    {1,2,3}, // dimension 3
                                    {4,5,6},
                                    {7,8,9},
                                    {2,4,5}
                                 }
                              }; // right way

Size of array [2][4][3]
Max indices   [1][3][2]

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.