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

后端 未结 6 1766
悲哀的现实
悲哀的现实 2020-12-23 00:27

The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:

The arra

相关标签:
6条回答
  • 2020-12-23 00:40

    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;
    }
    
    0 讨论(0)
  • 2020-12-23 00:42

    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.

    0 讨论(0)
  • 2020-12-23 00:42

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

    0 讨论(0)
  • 2020-12-23 00:50

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

    0 讨论(0)
  • 2020-12-23 00:54

    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;
            }
        }
    
    0 讨论(0)
  • 2020-12-23 00:56
    String[] str = {};
    

    But

    return {};
    

    won't work as the type information is missing.

    0 讨论(0)
提交回复
热议问题