• Post Reply Bookmark Topic Watch Topic
  • New Topic

why this array initialization does not give an error?  RSS feed

 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int[][] array1 = {{1, 2, 3}, {}, {1, 2,3, 4, 5}};

it initializes 3 one dimentional array:
1 - {1, 2, 3}
2 - {}
3 - {1, 2,3, 4, 5}

but it only declares two dimensional arrays.

How come this is true?
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The type int[][] is not two-dimensional array of type int
It is one-dimensional array of type int[].
And int[] is one-dimensional array of type int.

So your declaration is perfectly legal. It creates 3 one-dimensional int arrays (type int[]) and then stores them in one-dimensional int[] array (type int[][]).

Remember, Java does not support multidimensional arrays.
 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry i'm confused... can you please explain it more?
Does it mean without initializing array, it is equivalent to:
int[][] array1 = new int[3][]?
or int[][] array1 = new int[2][]?


Why is it when
int[][] array1 = {{1, 2, 3}, {1, 2,3, 4, 5}}; >>>only 2- one dimensional array
it is same as

int[][] array1 = new array[2][];?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Liek wrote:sorry i'm confused... can you please explain it more?

Arrays in Java are one-dimensional, however they can contain anything you care to put in them, including arrays - so Java implements "multi-dimensional" arrays as arrays of arrays, not blocks (or matrices) of contiguous storage.

Does it mean without initializing array, it is equivalent to:
int[][] array1 = new int[3][]?

Pretty much (as you say, without the initialization though).

Arrays are simply another type of object.

Winston
 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all so much. I now understand it.

the first [] in the int[][] corresponds to how many int [] there are.

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!