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.

  • 相关阅读:
    PHP和Redis实现在高并发下的抢购及秒杀功能示例详解
    quartz问题记录-missed their scheduled fire-time
    java(MyEclipse)创建webservice和测试webservice
    Redis wind7 安装
    spring boot新建项目报错总结
    spring boot新建项目启动报:Unregistering JMX-exposed beans on shutdown
    oracle安装过程和创建本地数据库
    正则表达式记录
    java continue与break区别
    Linux查看日志方法总结(1)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/return-empty-arrays-or-collections-not-nulls.html
Copyright © 2011-2022 走看看