如何在 Java 中初始化长度为 0 的字符串数组?

2022-01-19 00:00:00 arrays initialization java

该方法的 Java 文档
String[] java.io.File.list(FilenameFilter 过滤器)
在退货说明中包含此内容:

The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:

如果目录为空或过滤器不接受任何名称,则数组将为空.

The array will be empty if the directory is empty or if no names were accepted by the filter.

我该如何做类似的事情并将字符串数组(或任何其他数组)初始化为长度为 0?

How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?

推荐答案

正如其他人所说,

new String[0]

确实会创建一个空数组.然而,数组有一个好处——它们的大小不能改变,所以你总是可以使用相同的空数组引用.所以在你的代码中,你可以使用:

will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:

private static final String[] EMPTY_ARRAY = new String[0];

然后在每次需要时返回 EMPTY_ARRAY - 无需每次都创建新对象.

and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.

相关文章