[Code optimization] returns a zero-length array or set.

Source: Internet
Author: User

To get rid of your habit of inheriting from the C language, we have no reason in Java to return NULL for arrays or collections.


private final List<Cheese> InStock =...;public Cheese[] getCheeses() {       if( InStock.size() ==0){            return null;       }}

This is a frequently used return mode, which means that when applying the cheese array, You need to determine whether the array is null.

Cheese[]  cheeses= shop.getCheeses();if(cheeses! =null){   ....}

If we modify the array to be null or the set has no data, a 0 length will be returned, so that it will not be judged during use.

Whether the array and set are empty.


Some people think that the NULL return value is better than the 0-length array because it avoids the overhead required to allocate the array.

This viewpoint is untenable for two reasons. First, it is not advisable to worry about performance issues at this level, because the performance consumption at this level

It is insignificant; second, it is possible to freely share any element object without returning it.


In short, there is no reason to return NULL if the return type is array or set. We use an array or set with a return length of 0.

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.