overexchange
overexchange

Reputation: 1

Why java allows zero length index(in middle) array?

javac allows below syntax,

int[][][] i = new int[4][0][2];

which has zero length index that prevents access beyond.

1) There is no way to access third dimension. zero length dimension as last dimension(int[][][] i = new int[4][2][0];) looks fine.

2) It is not possible to write an initialiser for a multi-dimensional array with a zero length dimension unless that dimension is the last( for instance int[2][3][0]).

Why java allows such syntax?

Note: this question has nothing to do with int[0]

Upvotes: 2

Views: 114

Answers (4)

Malt
Malt

Reputation: 30335

First of all, it's not just in "the middle". You can easily define a one dimensional array just as easily:

int[] a = new int[0];

Second, an array with zero length is a bit like an empty collection. It's a legal data structure which might be returned by a method, but which happens to be empty.

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65851

So you can do perfectly acceptable stuff like:

public static final int[][][] EMPTYARRAY = new int[0][0][0];

note also things a much worse than you suppose because this is also legal:

public static final int[] SCREWEDARRAY = new int[-1];

which causes a runtime error:

java.lang.ExceptionInInitializerError
Caused by: java.lang.NegativeArraySizeException

Upvotes: 0

fge
fge

Reputation: 121780

Because nothing in the multianewarray bytecode instruction prevents you from doing so.

There is really no better answer than that... The fact is that for any X, even if X is a primitive, then X[] is a class, X[][] is a class and so on; and you are free to choose the "dimensions" of the array.

Note how declaring a X[n][] and a X[n][m] array differ: in the first you'll declare a anewarray of X[] whereas in the second you'll declare a multianewarray of X.

Of course, in X[m][n][p], there is no possibility to ever have a "third dimension" (p) if n is 0, but... Well, the programmer knows what he's doing, right?

Just another bizarreness of arrays in the JVM... Think nothing of it except that "it can happen" ;)

Upvotes: 3

Sh4d0wsPlyr
Sh4d0wsPlyr

Reputation: 968

I agree with @m0skit0 - I think this is a duplicate questions. However I will give a brief answer anyways.

Basically its an alternative for null. Consider simply, you have a method that returns an array, but it has no value to return. You could return null, but then you have to check for null in your code. On the other hand, you could return a 0 length array. Code such as the follows would automatically be skipped.

for(int p = 0; p < array.length; p++) {

Upvotes: 1

Related Questions