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

JavaArraysInitialization

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

String[] str = {};

But

return {};

won't work as the type information is missing.

Solution 4 - Java

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];

Solution 5 - Java

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;
        }
    }

Solution 6 - Java

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;
}

Solution 7 - Java

You can use following things-

1. String[] str = new String[0];
2. String[] str = ArrayUtils.EMPTY_STRING_ARRAY;<br>

Both are same.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRon TuffinView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavamaurisView Answer on Stackoverflow
Solution 3 - JavaThomas JungView Answer on Stackoverflow
Solution 4 - JavaRon TuffinView Answer on Stackoverflow
Solution 5 - Javafreak0View Answer on Stackoverflow
Solution 6 - JavaSwapnil GangradeView Answer on Stackoverflow
Solution 7 - JavadynamoView Answer on Stackoverflow