为什么Java允许大小为0的数组?

时间:2023-02-06 22:32:59

Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?

java中的数组是固定长度的。为什么Java允许大小为0的数组?

String[] strings = new String[0];

9 个解决方案

#1


96  

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.

从而避免了检查的必要。如果问题中的数组为空,则会出现异常,但在这种情况下,它什么也不做,这可能是适当的。

#2


47  

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?

为什么Java允许大小为1的数组?在数组中包装一个值不是很有用吗?如果Java只允许大小为2或更大的数组,这是否足够?

Yes, we can pass null instead of an empty array and a single object or primitive instead of a size-one-matrix.

是的,我们可以传递null,而不是一个空数组和一个对象或原语,而不是一个大小为一个的矩阵。

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.

将数组限制为大小[1.整数。我们必须添加许多额外的边界检查,(同意Konrads注释)转换逻辑和方法重载到我们的代码。从允许的数组大小中排除0(或者1)并不能节约成本,这需要额外的努力,并且对性能有负面影响。

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 ("").

Sidenote——一个(char-)数组的突出包装器是String类。不可变字符串具体化了空数组的概念:它是空字符串(“”)。

#3


20  

Sometimes it's much more friendly to return a zero size array than null.

有时返回零大小的数组比返回null要好得多。

#4


11  

Consider this (a more detailed explanation of Noon's answer):

想想这个(更详细地解释中午的答案):

public String[] getStrings() {
 if( foo ) {
  return null;
 } else {
  return new String[] {"bar, "baz"};
 }
}

String[] strings = getStrings();
if (strings != null) {
 for (String s : strings) {
  blah(s);
 }
}

Now compare it to this:

现在比较一下:

public String[] getStrings() {
 if( foo ) {
  return new String[0];
 } else {
  return new String[] {"bar, "baz"};
 }
}

// the if block is not necessary anymore
String[] strings = getStrings();
for (String s : strings) {
 blah(s);
}

This (returning empty arrays rather than null values), is in fact a best practice in Java API design world.

这(返回空数组而不是null值)实际上是Java API设计领域的最佳实践。

Besides, in Java, you can covert Lists (e.g. ArrayList) to arrays and it only makes sense to convert an empty list to an empty array.

此外,在Java中,您可以将列表(例如ArrayList)隐藏到数组中,只需要将空列表转换为空数组即可。

#5


5  

Same as C++, it allows for cleaner handling when there is no data.

与c++相同,它允许在没有数据时进行更干净的处理。

#6


4  

Another case where a zero length array can be useful: To return an array containing all of the elements in a list :

另一种情况下,零长度数组是有用的:返回包含列表中所有元素的数组:

<T> T[ ] toArray(T[ ] a)

A zero length array can be used to pass the type of the array into this method. For example:

一个零长度的数组可以用来将数组的类型传递到这个方法中。例如:

ClassA[ ] result = list.toArray(new ClassA[0]);

A zero length array is still an instance of Object which holds zero elements.

一个零长度的数组仍然是一个包含零元素的对象的实例。

#7


2  

One case I can think of where an empty array is extremely useful is to use it instead of null in a situation where null isn't allowed. One possible example of that is a BlockingQueue of arrays. When you want to signal the end of input to the reading side, what would you do? To send null seems like an obvious choice, but the thing is that BlockingQueue doesn't accept nulls. You could wrap your array inside a class with "boolean last;" kind of field, but that's kind of overkill. Sending an empty (zero-sized) array seems like the most reasonable choice.

我可以想到一个空数组非常有用的一个例子是在不允许null的情况下使用它而不是null。其中一个可能的例子是数组的BlockingQueue。当你想要将输入端信号发送到读取端时,你会怎么做?发送null似乎是一个显而易见的选择,但问题是阻塞队列不接受null。你可以在一个类中使用“布尔last”来包装数组,但这有点过分了。发送一个空的(零大小)数组似乎是最合理的选择。

#8


2  

only a note:

只有注意:

You say: "Unlike in C, where you can dynamically increase the size of an array,.." but in C you cannot change the dimension of array, the same for C++.

你说:“不像C,你可以动态地增加数组的大小。”但是在C中,你不能改变数组的维数,对于c++来说是一样的。

#9


0  

Another case when a zero length array is useful is when copying a two dimensional array. I can write:

当复制一个二维数组时,一个零长度数组是有用的。我可以写:

public int[][] copyArray(int[][] array){
     int[][] newArray = new int[array.length][0];
     for(int i=0;i<array.length;i++){
         newArray[i] = array[i];
     }
     return newArray;

Being that every array reference in array is being overwritten, initializing them as refernces to zero length arrays is most efficient.

由于数组中的每个数组引用都被覆盖,因此将它们初始化为零长度数组的引用是最有效的。

#1


96  

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.

从而避免了检查的必要。如果问题中的数组为空,则会出现异常,但在这种情况下,它什么也不做,这可能是适当的。

#2


47  

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?

为什么Java允许大小为1的数组?在数组中包装一个值不是很有用吗?如果Java只允许大小为2或更大的数组,这是否足够?

Yes, we can pass null instead of an empty array and a single object or primitive instead of a size-one-matrix.

是的,我们可以传递null,而不是一个空数组和一个对象或原语,而不是一个大小为一个的矩阵。

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.

将数组限制为大小[1.整数。我们必须添加许多额外的边界检查,(同意Konrads注释)转换逻辑和方法重载到我们的代码。从允许的数组大小中排除0(或者1)并不能节约成本,这需要额外的努力,并且对性能有负面影响。

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 ("").

Sidenote——一个(char-)数组的突出包装器是String类。不可变字符串具体化了空数组的概念:它是空字符串(“”)。

#3


20  

Sometimes it's much more friendly to return a zero size array than null.

有时返回零大小的数组比返回null要好得多。

#4


11  

Consider this (a more detailed explanation of Noon's answer):

想想这个(更详细地解释中午的答案):

public String[] getStrings() {
 if( foo ) {
  return null;
 } else {
  return new String[] {"bar, "baz"};
 }
}

String[] strings = getStrings();
if (strings != null) {
 for (String s : strings) {
  blah(s);
 }
}

Now compare it to this:

现在比较一下:

public String[] getStrings() {
 if( foo ) {
  return new String[0];
 } else {
  return new String[] {"bar, "baz"};
 }
}

// the if block is not necessary anymore
String[] strings = getStrings();
for (String s : strings) {
 blah(s);
}

This (returning empty arrays rather than null values), is in fact a best practice in Java API design world.

这(返回空数组而不是null值)实际上是Java API设计领域的最佳实践。

Besides, in Java, you can covert Lists (e.g. ArrayList) to arrays and it only makes sense to convert an empty list to an empty array.

此外,在Java中,您可以将列表(例如ArrayList)隐藏到数组中,只需要将空列表转换为空数组即可。

#5


5  

Same as C++, it allows for cleaner handling when there is no data.

与c++相同,它允许在没有数据时进行更干净的处理。

#6


4  

Another case where a zero length array can be useful: To return an array containing all of the elements in a list :

另一种情况下,零长度数组是有用的:返回包含列表中所有元素的数组:

<T> T[ ] toArray(T[ ] a)

A zero length array can be used to pass the type of the array into this method. For example:

一个零长度的数组可以用来将数组的类型传递到这个方法中。例如:

ClassA[ ] result = list.toArray(new ClassA[0]);

A zero length array is still an instance of Object which holds zero elements.

一个零长度的数组仍然是一个包含零元素的对象的实例。

#7


2  

One case I can think of where an empty array is extremely useful is to use it instead of null in a situation where null isn't allowed. One possible example of that is a BlockingQueue of arrays. When you want to signal the end of input to the reading side, what would you do? To send null seems like an obvious choice, but the thing is that BlockingQueue doesn't accept nulls. You could wrap your array inside a class with "boolean last;" kind of field, but that's kind of overkill. Sending an empty (zero-sized) array seems like the most reasonable choice.

我可以想到一个空数组非常有用的一个例子是在不允许null的情况下使用它而不是null。其中一个可能的例子是数组的BlockingQueue。当你想要将输入端信号发送到读取端时,你会怎么做?发送null似乎是一个显而易见的选择,但问题是阻塞队列不接受null。你可以在一个类中使用“布尔last”来包装数组,但这有点过分了。发送一个空的(零大小)数组似乎是最合理的选择。

#8


2  

only a note:

只有注意:

You say: "Unlike in C, where you can dynamically increase the size of an array,.." but in C you cannot change the dimension of array, the same for C++.

你说:“不像C,你可以动态地增加数组的大小。”但是在C中,你不能改变数组的维数,对于c++来说是一样的。

#9


0  

Another case when a zero length array is useful is when copying a two dimensional array. I can write:

当复制一个二维数组时,一个零长度数组是有用的。我可以写:

public int[][] copyArray(int[][] array){
     int[][] newArray = new int[array.length][0];
     for(int i=0;i<array.length;i++){
         newArray[i] = array[i];
     }
     return newArray;

Being that every array reference in array is being overwritten, initializing them as refernces to zero length arrays is most efficient.

由于数组中的每个数组引用都被覆盖,因此将它们初始化为零长度数组的引用是最有效的。