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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With