[ACCEPTED]-zero length arrays-java

Accepted answer
Score: 37

If you have a function that takes an array, and 5 you want to give it an array with nothing 4 in it, you pass an zero-length array.

If 3 you read an array from an external source, and 2 it happens to not have any items, you'll 1 get an zero-length array.

Score: 11

Assuming you mean in Java, you can iterate 4 over zero-length arrays without any problem 3 but you can't do this, if the variable is 2 set to null.

String[] myArr = new String[0];
for (String str : myArr) {
  // do something here

If you set myArr to null instead, you'd get 1 a NullPointerException in this loop.

Score: 6

There is no reason not to allow zero-length 8 arrays and supporting them avoid having 7 to special case many things.

For example: What 6 should the compiler pass to varArg if a method 5 defined like this:

public void foo(String arg1, String... varArg);

is called like this:


Also, what 4 should be the return value of "".toByteArray("UTF-8")?

Forbidding 3 zero-length arrays would complicate the 2 language considerably while adding very 1 little advantage.

Score: 5

They let you keep an API consistent while 10 avoiding null values. For instance, say 9 you have a method that returns an array 8 of something. If there are no valid results, you 7 would return a zero length array. If instead 6 you were forced to return null to signal 5 this, the client code would have to treat 4 the two cases differently. With the zero 3 length array, code like the following still 2 works:

for (int i = 0; i < array.length; i++) {
   // do something with the array entries

If array.length == 0, then the body 1 of the loop is never entered.

Score: 1

It avoids from having to check for null 2 if the precondition is that an array is 1 always present.

Score: 0

What is the purpose of an object with no 3 methods, members, or behavior? An array 2 is just a pointer to a contiguous block 1 of memory, so 0 is a valid length.

More Related questions