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

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?

This question is related to java arrays initialization

The answer is


String[] str = {};

But

return {};

won't work as the type information is missing.


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

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


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


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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization