Tuesday, March 1, 2011

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?

From stackoverflow
  • 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];

    Jonathan Leffler : Add such commentary to your question...or select one of the answers which said the same thing.
    Ron Tuffin : Thanks for the comment Jonathan. As you might have noticed I posted this answer before anyone else (and as such there were no answers to select). I also don't see how adding the answer to the question makes for a better question.
  • String[] str = new String[0];?

  • String[] str = {};
    

    But

    return {};
    

    won't work as the type information is missing.

    Bombe : `return new String[] { };` and `return new String[0];` would both work.
  • 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.

    Thomas Jung : It seems that everybody likes typing: `private static final String[] EMPTY_ARRAY = {};`
    Jon Skeet : @Thomas: I take your point, but for this particular case I prefer the more explicit form. It's clearer to me that it means "I want a string array with 0 elements" rather than "I want an array with this content - which is empty". Just personal preference I guess.
    Thomas Jung : @Tony - I have to use the few places where Java can infer a type. :-)

0 comments:

Post a Comment