java 为什么 int[] a = new int[0]; 允许吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13444414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:44:31  来源:igfitidea点击:

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

java

提问by Martin Thoma

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.

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..

myArray is not null..

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

所以我看不出为什么int[] myArray = new int[0]应该优先于myArray = null;.

回答by mishadoff

It's just for reducing null checks.

这只是为了减少空检查。

You can iterate on emptyarray but can not iterate on null.

您可以对数组进行迭代,但不能对 null 进行迭代。

Consider the code:

考虑代码:

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

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

在空数组上它不打印任何内容,在 null 上它会导致NullPointerException.

回答by SJuan76

Why not?

为什么不?

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

您可以获得一个包含目录中.exe文件列表的数组。并且该目录可以没有.exe文件。

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

null在这种情况下强制使用使创建和处理数组的逻辑变得复杂,并且毫无帮助。

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.

更新:更重要的是,Java 中的数组大小是在编译时决定的。确实new int[0]可以在编译时检测到,但new int[System.currentTimeMillis % 10]不能。因此,在编译时检查 0 大小写并不能确保您不会得到空数组。

回答by Petar Minchev

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 nullreference.

这将适用于空数组,但不适用于null参考。

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

您只需保存一个多余的null检查。例如,这就是为什么您还可以创建一个空列表的原因。

回答by Bela Vizer

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

是的,例如没有命令行参数的主方法执行。它为您提供了一个 0 大小的数组而不是 null。

回答by Michael Petrotta

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);
}

回答by rai.skumar

 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.

Java 中的数组是常规对象。所以上面的代码说数组大小为零。这对于防止空指针异常特别有用。

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

与此类似,甚至 Collections API 也有一种初始化为空占位符的方法。

 List<String> list = Collections.EMPTY_LIST;

回答by Malvon

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
}