Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multidimensional Array Assignments

 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Experimenting with the following code:
byte[][] b1 = new byte[4][4];
byte[][] b2 = new byte[2][2];
byte[][][][] b3 = new byte[5][6][7][8];
A. b1[1][0] = b2; //found: byte[][] required: byte
B. b3[1] = b2; //found: byte[][] required: byte[][][]
C. b3[1][1] = b2; //OK
D. b3[1][1][1] = b2; //found: byte[][] required: byte[]
I think I understand A and C, but can someone explain B and D.
 
Santhosh Kumar
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roger,
1. Basically there is no multidimensional array concept in java.
2. Array are themselves objects and can hold reference to other objects.
From point 2, you can create array which holds object reference to other array, simulating the multidimensional array.
To answer your question,
B: b3 is array of (array of (array of (array of (bytes))))
b3[1] is array of (array of (array of (bytes))) but where b2 is array of (array of (bytes)). So you cannot assign it.
D: b3[1][1][1] is array of (bytes). So you cannot assign b2 which is array of ((array of (bytes))
Hope this helps.
Santhosh.
[ April 18, 2003: Message edited by: Santhosh Kumar ]
 
Nico Schlebusch
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roger,
When you assign a value to an one-dimensional array you assign a specific value (primitive / reference) to a position in the array. E.g.

When you have a two-dimensional array you must assign a specific value to each position in the array or you can assign a one-dimensional array to a position in the array. E.g.

OR

As you can see in the last piece of code, the dimension of the array on the right-hand side of the = is one dimension less than the dimension of the array to the left of the =.
Thus, for your var b3 (a 4 dimensional array) in B you must assign a 3 dimensional array to a specific position:

For D, you need a one-dimensional array:

Hope this helps.
Nico
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it! And I now also understand why this is wrong:
b3[1][1][1][1] = b2;
And why this is right:
b3[1][1][1][1] = 1;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic