zoukankan      html  css  js  c++  java
  • Effective Java 43 Return empty arrays or collections, not nulls

    Feature

    Return empty arrays or collection

    Return nulls

    Avoids the expense of allocating the array

    N

    Y

    Return value is immutable which may be shared freely

    Y

    N

       

    Standard idiom for dumping items from a collection into a typed array

       

    public class Shop {

    // The right way to return an array from a collection

    private final List<Cheese> cheesesInStock = new ArrayList<Cheese>();

       

    // This prevent allocating an new Array every time which handles the expense issue.

    private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];

       

    /**

    * @return an array containing all of the cheeses in the shop.

    */

    public Cheese[] getCheeses() {

    return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);

    }

       

    public static void main(String[] args) {

    Shop shop = new Shop();

    // User don't have to check the null of the returned array since it always returns an empty array

    if (Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON))

    System.out.println("Jolly good, just the thing.");

    }

    }

       

       

    A collection-valued method can be made to return the same immutable empty collection every time it needs to return an empty collection.

    /**

    * The right way to return a copy of a collection

    * @return an array containing all of the cheeses in the shop.

    */

    public List<Cheese> getCheeseList() {

    if (cheesesInStock.isEmpty())

    return Collections.emptyList(); // Always returns same list

    else

    return new ArrayList<Cheese>(cheesesInStock); // This is defensive copy to avoid the mutable object to be modified by the client.

    }

       

    Summary

    There is no reason ever to return null from an array or collection-valued method instead of returning an empty array or collection.

  • 相关阅读:
    Linux安装gitlab
    logback日志配置
    spring源码-aop动态代理-5.3
    【转】阿里云免费SSL证书申请与安装使用(IIS7)
    WebApi 全局使用filter
    Mint-UI Picker 三级联动
    P标签莫名有了margin-top值的原因
    Vue为v-html中标签添加CSS样式
    【转】C# string数组转int数组
    【转】SQLServer汉字转全拼音函数
  • 原文地址:https://www.cnblogs.com/haokaibo/p/return-empty-arrays-or-collections-not-nulls.html
Copyright © 2011-2022 走看看