這個方法主要用於只有一個元素的優化,減少內存分配,無需分配額外的內存,可以從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);