如何在Java中初始化长度为0的String数组? [英] How can I initialize a String array with length 0 in Java?

查看:1168
本文介绍了如何在Java中初始化长度为0的String数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法的Java文档

String [] java.io.File.list(FilenameFilter filter)

在返回描述中包含此内容:

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.

如何进行类似的操作并初始化一个String数组(或任何其他数组),使其长度为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.

这篇关于如何在Java中初始化长度为0的String数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆