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

后端 未结 6 1803
悲哀的现实
悲哀的现实 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: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.

提交回复
热议问题