返回零長度的數組或者集合,而不是null——Effective Java 讀書筆記,nulleffective

來源:互聯網
上載者:User

返回零長度的數組或者集合,而不是null——Effective Java 讀書筆記,nulleffective

/** * 返回零長度的數組或者集合,而不是null *  * @author 劉向峰 *  */public class Shop {    private List<Object> objectList;    // 零長度常數陣列被傳遞給toArray方法,以指明所期望的傳回型別    private final static Object[] EMPTY_OBJECT_ARRAY = new Object[0];    public Shop(List<Object> objectList) {        super();        this.objectList = objectList;    }    /**     *      * @return an array containing all of the object in the shop     */    public Object[] getObjects() {        // 如果集合是空的,他將使用零長度的輸入數組-->否則,這種做法永遠不會分配零長度的數組        return objectList.toArray(EMPTY_OBJECT_ARRAY);    }    /**     *      * @return a copy of collection     */    public List<Object> getStringList() {        if (objectList.isEmpty()) {            return Collections.emptyList();        } else {            return new ArrayList<Object>(objectList);        }    }    /**     * 測試方法     *      * @param args     */    public static void main(String[] args) {        List<Object> newObjectList = Collections.emptyList();        // newObjectList = new ArrayList<Object>();        Object object = new Object();        // newObjectList.add(object);        Shop shop = new Shop(newObjectList);        // 不需要判斷shop.getObjects()的值是否為空白        if (Arrays.asList(shop.getObjects()).contains(object)) {            System.out.println("jolly good, just the thing");        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.