char[] arrNew = new char[0];
System.out.println(arrNew.length); // length = 0
arrNew[0]='c'; // ArrayIndexOutOfBoundsException .
In the above code as you can clearly see there is no point in having an array of size 0. As far as I can see there is no practical usage of 0 size array. Can someone explain why the compiler allows creation of 0 length array. And also how is a 0 length array different from an array initialized to null? (i.e, is memory allocated to it as if it were a normal array?). I am sorry if this question seems stupid.
Although the size of a zero-length array is zero, an array member of this kind may increase the size of the enclosing type as a result of tail padding. The offset of a zero-length array member from the beginning of the enclosing structure is the same as the offset of an array with one or more elements of the same type.
Arrays in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array. In other words, the index value of the first element in the array is “0” and the index value of the second element is “1”, the third element's index value is “2”, and so on.
The length property sets or returns the number of elements in an array.
length: The length property is used to find the array length. array[0]. length: The number of columns on row 0. array[1]. length: The number of columns on row 1.
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;
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With