如何在 Java 中初始化长度为 0 的字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1665834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I initialize a String array with length 0 in Java?
提问by Ron Tuffin
The Java Docs for the methodString[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:
该方法的 Java 文档String[] java.io.File.list(FilenameFilter filter)
在返回描述中包含以下内容:
The array will be empty if the directory is empty or if no names were accepted by the filter.
如果目录为空或过滤器不接受任何名称,则数组将为空。
How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?
我如何做类似的事情并将字符串数组(或任何其他数组)初始化为长度为 0?
采纳答案by Jon Skeet
As others have said,
正如其他人所说,
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];
and then just return EMPTY_ARRAY
each time you need it - there's no need to create a new object each time.
然后EMPTY_ARRAY
每次需要时都返回- 无需每次都创建一个新对象。
回答by Ron Tuffin
Ok I actually found the answer but thought I would 'import' the question into SO anyway
好的,我实际上找到了答案,但我认为无论如何我都会将问题“导入”到 SO
String[] files = new String[0];
orint[] files = new int[0];
String[] files = new String[0];
或者int[] files = new int[0];
回答by mauris
String[] str = new String[0];
?
String[] str = new String[0];
?
回答by Thomas Jung
String[] str = {};
But
但
return {};
won't work as the type information is missing.
将无法工作,因为缺少类型信息。
回答by Swapnil Gangrade
Make a function which will not return null instead return an empty array you can go through below code to understand.
制作一个不会返回 null 而是返回一个空数组的函数,您可以通过下面的代码来理解。
public static String[] getJavaFileNameList(File inputDir) {
String[] files = inputDir.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isFile() && (name.endsWith("java"));
}
});
return files == null ? new String[0] : files;
}
回答by freak0
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
您可以使用 org.apache.commons.lang3 中的 ArrayUtils.EMPTY_STRING_ARRAY
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}