Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Array of length 0? [duplicate]

Tags:

java

arrays

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.

like image 292
TheLostMind Avatar asked Jan 20 '14 10:01

TheLostMind


People also ask

What is an array of length 0?

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.

Does length of array include 0?

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.

What is the purpose of length in array?

The length property sets or returns the number of elements in an array.

What is array 0 .length in Java?

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.


1 Answers

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;
     }
     ...
like image 50
Evgeniy Dorofeev Avatar answered Oct 26 '22 05:10

Evgeniy Dorofeev