這個方法主要用于只有一個元素的優化,減少記憶體分配,無需分配額外的記憶體,可以從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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/119896.html
標籤:Java
