简体   繁体   中英

Why is int[] a = new int[0]; allowed?

Is there a reason why

int[] myArray = new int[0];

compiles?

Is there any use of such an expression?

myArray[0] = 1;

gives java.lang.ArrayIndexOutOfBoundsException .

if (myArray == null) {
    System.out.println("myArray is null.");
} else {
    System.out.println("myArray is not null.");
}

gives myArray is not null. .

So I can't see a reason why int[] myArray = new int[0] should be preferred over myArray = null; .

It's just for reducing null checks.

You can iterate on empty array but can not iterate on null.

Consider the code:

for (Integer i: myArray) {
   System.out.println(i);
}

On empty array it prints nothing, on null it causes NullPointerException .

Why not?

You can get an array with the list of .exe files in a directory. And that directory can have no .exe files.

Forcing to use null for this case complicated the logic both creating and handling the array and helps to nothing.

UPDATE: More the point, the array size in Java is decided at compile time. It is true that new int[0] can be detected at compile time, but new int[System.currentTimeMillis % 10] cannot. So checking the 0 case at compile time does not ensure that you don't get empty arrays.

For example:

public void getArraySum(int[] array) {
    int sum = 0;    

    for (int i = 0; i < array.length; i++)
        sum += array[i];

    return sum;
}

This will work with an empty array, but won't with null reference.

You just save a redundant null check. That is why you can create also an empty list for example.

Yes there is eg main method execution w/o command line parameters. It gives you a 0-sized array instead of null.

 int[] myArray = new int[0];

Arrays in java are regular objects. So above code says that array size is zero. This is particularly useful for protection against Null pointer exception .

Similar to this even Collections API have a way to initialize to an empty place holder.

 List<String> list = Collections.EMPTY_LIST;
public int[] getData()
{
    if (iGotNothinForYa)
    {
        return new int[0];
    }

    int[] data = buildUpArray();
    return data;
}

It's often easier, in code consuming the data returned by a method like this, to not have to do a null check. Particularly when iterating over the array.

int[] data = getData();
for (int i : data) // yay! no null check!
{
    doSomethingWith(i);
}

An empty array can be used in thread synchronization when the goal is to use the least amount of memory for a locking object. Recall that arrays are objects, so if you wish to synchronize multiple threads on a single dummy object, the smallest object you can utilize is an empty array (possibly byte size):

byte bLock = new byte[0];
// Thread T1 synchronizes on this empty array object
synchronize(bLock) {
    // perform some task while blocking other threads
    // synchronizing on bLock
}

The why new [0] returns null instead of [], is because the system acnnot allocate (no space), it needs to allocate at least 1. So that is why it returns null. A list is different because a list is a class somehow that internally has an array or tree or something similar so it manages it internally. but int[] is just an array and that is just those ints in memory. (so int[0], is actually nothing, so why will alocate to have nothing? is good it givse null). why is it allowed, well imagine you do new int [x+y]; where you do not know x, or y, and they can be both 0, without allowing this you need to check for it before and act different before eacn time.

As in the API Documentation , it can also be used like this:

String[] a = c.toArray(new String[0]); // c: List<String>

instead of calculating the array length yourself:

String[] a = new String[c.size()];
c.toArray(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM