How can I initialize a String array with length 0 in Java?(如何在 Java 中初始化长度为 0 的字符串数组?)
问题描述
该方法的 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.
这篇关于如何在 Java 中初始化长度为 0 的字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中初始化长度为 0 的字符串数组?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
