Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional arrays with different sizes

Tags:

I just had an idea to test something out and it worked:

    String[][] arr = new String[4][4];      arr[2] = new String[5];      for(int i = 0; i < arr.length; i++)     {         System.out.println(arr[i].length);     } 

The output obviously is:

4 4 5 4 

So my questions are:

  • Is this good or bad style of coding?
  • What could this be good for?
  • And most of all, is there a way to create such a construct in the declaration itself?
  • Also... why is it even possible to do?
like image 563
Loki Avatar asked Aug 01 '13 15:08

Loki


1 Answers

  • Is this good or bad style of coding?

Like anything, it depends on the situation. There are situations where jagged arrays (as they are called) are in fact appropriate.

  • What could this be good for?

Well, for storing data sets with different lengths in one array. For instance, if we had the strings "hello" and "goodbye", we might want to store their character arrays in one structure. These char arrays have different lengths, so we would use a jagged array.

  • And most of all, is there a way to create such a construct in the declaration itself?

Yes:

char[][] x = {{'h','e','l','l','o'},               {'g','o','o','d','b','y','e'}}; 
  • Also... why is it even possible to do?

Because it is allowed by the Java Language Specification, §10.6.

like image 103
arshajii Avatar answered Oct 02 '22 17:10

arshajii