Effective Java-----Returns an array or collection of 0 lengths instead of NULL

Source: Internet
Author: User

The following code, which normally returns NULL when the user list is empty, is assumed to be that the null return value is better than a zero-length array because it avoids the overhead required to allocate the array.

Private final list<userbean> userlist = null;public list<userbean> Getuserbean () {    if (userlist.size () = = 0) {        return null;    } else{        return userlist;}    }

But this view is untenable for the following reasons:

1) It is unwise to worry about performance issues at this level unless the analysis shows that this approach is the real source of performance problems;
2) It is possible to return a 0-length array every time for calls that do not return any elements, since 0-length arrays are immutable, and immutable objects may be freely shared.

Therefore, you can return a collection of 0 lengths as follows:

Public list<userbean> getuserbeanmodify () {    if (Userlist.isempty ()) {        return collections.emptylist ();    } else{        return userlist;}    }

In summary, it is important to note that the return type is an array or a method of a collection, and there is no reason to return null, but to return a 0-length arrays or collections.

Effective Java-----Returns an array or collection of 0 lengths instead of NULL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.