[ACCEPTED]-zero length arrays-java
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.
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.
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:
foo("bar");
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.
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.
It avoids from having to check for null 2 if the precondition is that an array is 1 always present.
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.