Advertisement
Advertisement


How can I initialize a String array with length 0 in Java?


Question

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.

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

2009/11/03
1
134
11/3/2009 8:11:46 AM

Accepted Answer

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.

2009/11/03
232
11/3/2009 8:09:11 AM

String[] str = new String[0];?

2009/11/03

String[] str = {};

But

return {};

won't work as the type information is missing.

2009/11/03

Ok I actually found the answer but thought I would 'import' the question into SO anyway

String[] files = new String[0];
or
int[] files = new int[0];

2009/11/03

You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3

import org.apache.commons.lang3.ArrayUtils;

    class Scratch {
        public static void main(String[] args) {
            String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
        }
    }
2018/05/30

Make a function which will not return null instead return an empty array you can go through below code to understand.

    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;
}
2017/03/20

Source: https://stackoverflow.com/questions/1665834
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]