If you have a function that takes an array, and you want to give it an array with nothing in it, you pass an zero-length array.
If you read an array from an external source, and it happens to not have any items, you'll get an zero-length array.
Answer from SLaks on Stack OverflowIf you have a function that takes an array, and you want to give it an array with nothing in it, you pass an zero-length array.
If you read an array from an external source, and it happens to not have any items, you'll get an zero-length array.
Assuming you mean in Java, you can iterate over zero-length arrays without any problem but you can't do this, if the variable is 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 a NullPointerException in this loop.
java - Use of Array of length 0? - Stack Overflow
How can I initialize a String array with length 0 in Java? - Stack Overflow
Why are zero-length arrays allowed?
java - Use of array of zero length - Stack Overflow
It signifies that it is empty. I.e. you can loop over it as if it had items and have no result occur:
for(int k = 0; k < strings.length; k++){
// something
}
Thereby avoiding the need to check. If the array in question were null, an exception would occur, but in this case it just does nothing, which may be appropriate.
Why does Java allow arrays of size 1? Isn't it pretty useless to wrap a single value in an array? Wouldn't it be sufficient if Java only allowed arrays of size 2 or greater?
Yes, we can pass null instead of an empty array and a single object or primitive instead of a size-one-matrix.
But there are some good arguments against such an restriction. My personal top arguments:
Restriction is too complicated and not really necessary
To limit arrays to sizes [1..INTEGER.MAX_INT] we'd have to add a lot of additional boudary checks,(agree to Konrads comment) conversion logic and method overloads to our code. Excluding 0 (and maybe 1) from the allowed array sizes does not save costs, it requires additional effort and has an negative impact on performance.
Array models vector
An array is a good data model for a vector (mathematics, not the Vector class!). And of course, a vector in mathematics may be zero dimensional. Which is conceptually different from being non-existant.
Sidenote - a prominent wrapper for an (char-)array is the String class. The immutable String materializes the concept of an empty array: it is the empty String ("").
We can return an empty array instead of null from a method, this is called Null object design pattern. Consider the following code
Person[] res = find(name);
for(String e : res) {
System.out.println(e);
}
if find() does not find anyone it returns an empty array. If find returned null then code would need to treat it as a special case.
We should keep in mind that empty array is immutable so it is logical to use a singleton instead of creating it each time
private static final Person[] NULL = new Person[0];
Person[] find(String name) {
...
if (notFound) {
return NULL;
}
...
It's best not to return null from a method that returns an array type. Always returning an array, even if the array has zero length, greatly improves the generality of algorithms. If you anticipate that your methods will return zero-length arrays frequently, you might be concerned about the performance implications of allocating many such arrays. To solve that problem, simply allocate a single array, and always return the same one, for example:
private static final int ZERO_LENGTH_ARRAY[] = new int[0];
This array is immutable (it can't be changed), and can be shared throughout the application.
So in Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available.
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.
String[] str = new String[0];?
In Java this compiles fine:
String[] strings = new String[0];
Why is that? Any attempt to access it, such as saying "strings[0]" throws an ArrayIndexOutOfBoundsException. Shouldn't this just not compile?
An example. Say, you have a function
public String[] getFileNames(String criteria) {
to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.
The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).
There's a chapter on this in Effective Java, Item 27
It's easier to work with than null in many cases, where null is the obvious alternative.
Suppose you want to return an Iterable<String> containing (say) a list of relevant filenames... but there aren't any for some reason. You could return null to indicate that, but then the caller has to special-case that. Instead, if you return an empty collection, the caller can still use an enhanced for loop:
for (String file : getFiles())
So why use an empty array instead of an empty ArrayList or something similar? Arrays are a fixed size, so an empty array is effectively immutable. That means you can keep a single value and return it to whoever you like, knowing they can't possibly do anything with it. That can be very useful in some situations.
No, this can never happen. The length is guaranteed to be non-negative as per the Java specifications.
The members of an array type are all of the following:
- The public final field length, which contains the number of components of the array. length may be positive or zero.
Source: JLS ยง10.7
As mprivat mentioned, if you ever try to create an array of negative size, a NegativeArraySizeException will be thrown.
I don't believe it's possible. Even through reflection, it is guarded with NegativeArraySizeException
The issue I would wager is that C arrays are just pointers to the beginning of an allocated chunk of memory. Having a 0 size would mean that you have a pointer to... nothing? You can't have nothing, so there would have had to be some arbitrary thing chosen. You can't use null, because then your 0 length arrays would look like null pointers. And at that point every different implementation is going to pick different arbitrary behaviors, leading to chaos.
Let's look at how an array is typically laid out in memory:
+----+
arr[0] : | |
+----+
arr[1] : | |
+----+
arr[2] : | |
+----+
...
+----+
arr[n] : | |
+----+
Note that there isn't a separate object named arr that stores the address of the first element; when an array appears in an expression, C computes the address of the first element as needed.
So, let's think about this: a 0-element array would have no storage set aside for it, meaning there's nothing to compute the array address from (put another way, there's no object mapping for the identifier). It's like saying, "I want to create an int variable that takes up no memory." It's a nonsensical operation.
Edit
Java arrays are completely different animals from C and C++ arrays; they're not a primitive type, but a reference type derived from Object.
Edit2
A point brought up in the comments below - the "greater than 0" constraint only applies to arrays where the size is specified through a constant expression; a VLA is allowed to have a 0 length Declaring a VLA with a 0-valued non-constant expression is not a constraint violation, but it does invoke undefined behavior.
It's clear that VLAs are different animals from regular arrays, and their implementation can allow for a 0 size. They cannot be declared static or at file scope, because the size of such objects must be known before the program starts.
It's also worth nothing that as of C11, implementations are not required to support VLAs.
If you think of Block[][] as being rows and columns of Block, and each row being a Block[] of columns, and an array of rows would be a Block[][], then:
block.length // the number of rows
block[0].length // the number of columns on row 0
block[1].length // the number of columns on row 1
// etc
What do you expect? You have a multi dimensional array. Thus, there is more than one dimension. Each dimension has a length. With block.length you get the length of the first one (i.e. 50), with block[x].length, you get the length of the second one (i.e., 70).
Since you allocated your array like this, all block[x].length will be equal, no matter what you choose for x. However, you could have an array where the nested arrays have different lengths, then block[0].length might not be equal to block[1].length.