views:

707

answers:

4

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?

A: 

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

Ron Tuffin
Add such commentary to your question...or select one of the answers which said the same thing.
Jonathan Leffler
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.
Ron Tuffin
+8  A: 

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

thephpdeveloper
+2  A: 
String[] str = {};

But

return {};

won't work as the type information is missing.

Thomas Jung
`return new String[] { };` and `return new String[0];` would both work.
Bombe
+7  A: 

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.

Jon Skeet
It seems that everybody likes typing: `private static final String[] EMPTY_ARRAY = {};`
Thomas Jung
@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.
Jon Skeet
@Tony - I have to use the few places where Java can infer a type. :-)
Thomas Jung