零长度数组的使用 [英] Use of array of zero length
问题描述
例如我们可以像这样构造这样一个数组:
For example we can construct such an array like this:
new ElementType[0];
我看到过这样的结构,但我不明白为什么这可能有用.
I seen such a construct, but I don't understand why this might be useful.
推荐答案
一个例子.说,你有一个功能
An example. Say, you have a function
public String[] getFileNames(String criteria) {
获取一些文件名.想象一下,您没有找到任何满足条件的文件名.你回什么?您有 2 个选择 - 返回 null 或 0 大小的数组.
to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.
0 大小数组的变体更好,因为您的调用者不需要检查 NULL 并且可以以一致的方式处理数组 - 例如,在循环中(在这种情况下为空).
The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).
这篇关于零长度数组的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!