Arrays.asList() 和Collections.singletonList()的區別


1.Arrays.asList()返回值是仍然是一個可變的集合,但是返回值是其內部類,不具有add方法,可以通過set方法進行增加值,默認長度是10

2.Collections.singletonList()返回的是不可變的集合,但是這個長度的集合只有1,可以減少內存分配,無需分配額外的內存。可以從SingletonList內部類看得出來,由於只有一個element,因此可以做到內存分配最小化,相比之下ArrayList的DEFAULT_CAPACITY=10個。但是返回的值依然是Collections的內部實現類,同樣沒有add的方法,調用add,set方法會報錯。

源碼:

/**
     * 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> orderNos = Collections.singletonList(orderNo);

如何將一個元素優雅的轉換成一個集合:

List<String> list = Stream.of(str1).collect(Collectors.toList());

 


免責聲明!

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



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