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 的字符串数组?
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Maven:无效的目标版本:10 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
