简体   繁体   English

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

[英]Why does Java allow arrays of size 0?

Arrays in java are fixed in length. java中的数组的长度是固定的。 Why does Java allow arrays of size 0 then? 为什么Java允许大小为0的数组呢?

String[] strings = new String[0];

It signifies that it is empty. 它表示它是空的。 Ie 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. 如果有问题的数组为null ,则会发生异常,但在这种情况下,它只会执行任何操作,这可能是合适的。

Why does Java allow arrays of size 1? 为什么Java允许大小为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只允许大小为2或更大的数组,那还不够吗?

Yes, we can pass null instead of an empty array and a single object or primitive instead of a size-one-matrix. 是的,我们可以传递null而不是空数组和单个对象或基元而不是size-one-matrix。

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. 要将数组限制为大小[1..INTEGER.MAX_INT],我们必须添加 许多额外的boudary检查 (同意Konrads注释)转换逻辑和方法重载到我们的代码。 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. 从允许的阵列大小中排除0(可能是1)不会节省成本,它需要额外的工作量并对性能产生负面影响。

Array models vector 数组模型矢量

An array is a good data model for a vector (mathematics, not the Vector class!). 数组是向量的一个很好的数据模型(数学, 而不是 Vector类!)。 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. Sidenote - (char-)数组的显着包装器是String类。 The immutable String materializes the concept of an empty array: it is the empty String ( "" ). 不可变的String实现了一个空数组的概念:它是空字符串( "" )。

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

Consider this (a more detailed explanation of Noon's answer): 考虑一下(对Noon答案的更详细解释):

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. 这(返回空数组而不是空值)实际上是Java API设计世界中的最佳实践。

Besides, in Java, you can covert Lists (eg ArrayList) to arrays and it only makes sense to convert an empty list to an empty array. 此外,在Java中,您可以将列表(例如ArrayList)转换为数组,只有将空列表转换为空数组才有意义。

与C ++相同,它允许在没有数据时更清晰地处理。

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. 零长度数组仍然是Object的一个实例,它包含零个元素。

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. 我可以想到一个空数组非常有用的地方是在不允许null的情况下使用它而不是null。 One possible example of that is a BlockingQueue of arrays. 一个可能的例子是数组的BlockingQueue。 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. 发送null似乎是一个明显的选择,但问题是BlockingQueue不接受空值。 You could wrap your array inside a class with " boolean last; " kind of field, but that's kind of overkill. 您可以使用“ boolean last; ”类型的字段将数组包装在一个类中,但这有点过分。 Sending an empty (zero-sized) array seems like the most reasonable choice. 发送空(零大小)数组似乎是最合理的选择。

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. 由于数组中的每个数组引用都被覆盖,因此初始化它们作为零长度数组的引用是最有效的。

A 0-length byte[] , or char[] can represent an empty String , which is distinct from null . 0长度byte[]char[]可以表示空String ,它与null不同。 Getting the bytes, or characters, as arrays from strings (using getBytes() , getChars() of String class etc.) and the vice-versa of forming String s from byte[] , char[] is quite common. 从字符串中获取字节或字符作为数组(使用String类的getBytes()getChars()等),反之亦然,从byte[]char[]形成String s是很常见的。 For example, for custom encoding, decoding of strings. 例如,对于自定义编码,字符串的解码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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