Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I create a two dimensional array with 0 rows but 5 columns in java?

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.

like image 548
Ziyang Zhang Avatar asked Dec 03 '17 20:12

Ziyang Zhang


2 Answers

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.

like image 178
Makoto Avatar answered Oct 30 '22 19:10

Makoto


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 NullPointerExceptions 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:

warning light

like image 29
Funny Geeks Avatar answered Oct 30 '22 20:10

Funny Geeks