Tuesday, July 14, 2009

Returning Zero-Length Arrays in Java

It's best not to return null from a method that returns an array type. Always returning an array, even if the array has zero length, greatly improves the generality of algorithms. If you anticipate that your methods will return zero-length arrays frequently, you might be concerned about the performance implications of allocating many such arrays. To solve that problem, simply allocate a single array, and always return the same one, for example: private static final int ZERO_LENGTH_ARRAY[] = new int[0];
This array is immutable (it can't be changed), and can be shared throughout the application.

No comments:

Post a Comment