int[][] a = new int[0][5];
Why the above code is valid in java?
This 2d array is pretty much useless, because the first dimension is ZERO. Logically, if the first dimension is 0, the second dimension should not be bigger than 0.
I understand we can initiate a 1d empty array.
By the JLS, an array expression indicating a size of zero is valid - it is just an expression - so you can legally declare an n-dimensional array that has zero cardinality.
The only thing that JLS lexer checks (as of Java 8) is whether or not the expression evaluates to zero:
Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then a NegativeArraySizeException is thrown.
This says nothing of its usefulness, as I'm sure you're aware, any attempt to index into this array will produce an ArrayIndexOutOfBoundsException
since your index location starts at zero.
It shouldn't be weird to think as an empty array as something normal. There is a very similar case where we deal with empty arrays all the time.
List<String> names = new ArrayList<String>();
names
is currently an empty array. Wouldn't it be weird to always declare arrays with at least the first element?
List<String> names = new ArrayList<String>(Arrays.asList("John"));
The alternative to new int[0]
being valid syntax would be to set the array to null
when the first element is not available. In this world, we would be expected to regularly check for null
before iterating an array.
int[] nums = null; // Because empty primitive arrays are "weird"
//typical for-each loop
if(nums != null){
for(int x: nums){
// do something
}
}
//typical for loop
if(nums != null){
for(int c = 0; c < nums.length; c++){
// do something
}
}
Without empty arrays, regular for loops would throw NullPointerException
s all the time. All that said, it is weird to use new int[0][5]
instead of new int[0][]
. I don't think it's worthy of a syntax error, but I think it deserves one of these from the IDE:
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