I 开发者_运维百科was told to use zerolength arrays instead of nulls in the program.But I couldn't find how to use Zerolength array.Please Help me.
The idea, in general, is that if a query returns "no results", all things being equal, it is better to return an empty list (or array) than null
.
The reason for that is it makes the client code a lot cleaner. You can still do something like this with an empty array:
Account[] accounts = getAccounts();
for ( Account account : accounts ) {
account.recomputeForInterest();
}
If you tried the same with null
you would get a runtime exception. You can create an empty array using a few methods:
Account[] accounts = {};
accounts = new Account[0];
accounts = new Account[]{};
A zero-length array is simply an array with no contents. For example, a zero-length array of int
types would be:
int[] myArray = new int[0];
Choosing between null
and an empty array is simply a design decision, depending on how you wish to use the code. null
requires an extra check (e.g. if (myArray != null) { ... }
), but does not actually allocate any space, and therefore may be cheaper if space is of the essence.
A zero length array can be used as an array; you can iterate over its members, for example, or use .length. You can't do that with null because you will get a null reference exception.
Don't pass nulls!
If you pass a zero length array instead of null then a method using it will be able to iterate over it without causing a null pointer exception. The same is true for any collection class
精彩评论