Collections.singletonList方法


  這個方法主要用於只有一個元素的優化,減少內存分配,無需分配額外的內存,可以從SingletonList內部類看得出來,由於只有一個element,因此可以做到內存分配最小化,相比之下ArrayList的DEFAULT_CAPACITY=10個。

  

源碼:

 /**
     * Returns an immutable list containing only the specified object.
     * The returned list is serializable.
     *
     * @param  <T> the class of the objects in the list
     * @param o the sole object to be stored in the returned list.
     * @return an immutable list containing only the specified object.
     * @since 1.3
     */
    public static <T> List<T> singletonList(T o) {
        return new SingletonList<>(o);
    }

 

使用:

  


List<Integer> catalogIds = Collections.singletonList(catalogId);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM