Thoughts on "Return empty arrays or collections, not nulls"

Source: Internet
Author: User

Article 2 of objective java: Return empty arrays or collections, not nulls

It means that in the method that needs to return an array or set, if empty data needs to be returned, do not return null, but return an array or set with a size of 0.

In many cases, such code may appear:

 1 private final List<Cheese> cheesesInStock = ...;
2 /**
3 * @return an array containing all of the cheeses in the shop,
4 * or null if no cheeses are available for purchase.
5 */
6 public Cheese[] getCheeses() {
7   if (cheesesInStock.size() == 0)
8     return null;
9   ...
10 }

If no data exists, null is directly returned.

However, if this method is used, the client that calls the Code must determine whether the return value of this method is null. Otherwise, an NullPointerException exception may be thrown.

For example:

Code 1:

1 Cheese[] cheeses = shop.getCheeses();
2 if (cheeses != null &&
3 Arrays.asList(cheeses).contains(Cheese.STILTON))
4   System.out.println("Jolly good, just the thing.");

Each call must be judged to be null or not, and it is easy to forget the check to throw an exception.

Some people insist on returning null because they think it takes time and space to allocate an empty array or set, which affects performance. The author believes that:

1) This performance loss is negligible;

2) The returned empty array or set is usually immutable, that is, immutable. Therefore, you can define static final (for arrays) or Collections. emptyList ()/emptyMap ()/emptySet () to share the same object, reducing the performance impact.

Code 2:

1 // The right way to return an array from a collection
2 private final List<Cheese> cheesesInStock = ...;
3 private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
4 /**
5 * @return an array containing all of the cheeses in the shop.
6 */
7 public Cheese[] getCheeses() {
8   return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
9 }
 

Code 3:

1 // The right way to return a copy of a collection
2 public List<Cheese> getCheeseList() {
3   if (cheesesInStock.isEmpty())
4     return Collections.emptyList(); // Always returns same list
5   else
6     return new ArrayList<Cheese>(cheesesInStock);
7 }

Several ideas:

1) Try to comply with this specification when writing the interface method by yourself, and mark it in the method comment. Returns an array or set of 0 values.

2) The Collections. emptyList ()/emptyMap ()/emptySet () mentioned in this article must be used with caution. Because the collection objects returned by these methods are immutable, that is, they cannot be changed. Sometimes we may need to add or delete elements to the returned collection. In this case, the UnsupportedOperationException will be reported.

3) tips:

A) when you want to determine whether an element is in an array, you can use Arrays. asList (T [] array ). contains (T obj) is implemented without the need to iterate every element in a loop to determine.

B) as shown in Code 2, if you want to convert ArrayList into an array, you can use ArrayList. toArray (T [] array), where the array only needs to be set to an array with a size of 0. It is only used to specify the returned type, and T may be a subclass of the element in the ArrayList.

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.