Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of array of zero length

Tags:

java

arrays

For example we can construct such an array like this:

 new ElementType[0]; 

I seen such a construct, but I don't understand why this might be useful.

like image 777
Johanna Avatar asked Jun 24 '09 06:06

Johanna


1 Answers

An example. Say, you have a function

public String[] getFileNames(String criteria) { 

to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.

The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).

There's a chapter on this in Effective Java, Item 27

like image 186
Igor Krivokon Avatar answered Sep 18 '22 04:09

Igor Krivokon