Arrays.asList()和Collections.singletonList()比较
生活随笔
收集整理的這篇文章主要介紹了
Arrays.asList()和Collections.singletonList()比较
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Collections.singletonList(something)是不可變的,
對Collections.singletonList(something)返回的列表所做的任何更改將導致UnsupportedOperationException。
Arrays.asList(something)允許Arrays.asList(something) 更改 。
此外,由Collections.singletonList(something)返回的List的容量將始終為1,
? 而Arrays.asList(something)的容量將為已支持數組的大小。
* 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);}/*** @serial include*/private static class SingletonList<E>extends AbstractList<E>implements RandomAccess, Serializable {private static final long serialVersionUID = 3093736618740652951L;private final E element;SingletonList(E obj) {element = obj;}public Iterator<E> iterator() {return singletonIterator(element);}public int size() {return 1;}public boolean contains(Object obj) {return eq(obj, element);}public E get(int index) {if (index != 0)throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");return element;}// Override default methods for Collection@Overridepublic void forEach(Consumer<? super E> action) {action.accept(element);}@Overridepublic boolean removeIf(Predicate<? super E> filter) {throw new UnsupportedOperationException();}@Overridepublic void replaceAll(UnaryOperator<E> operator) {throw new UnsupportedOperationException();}@Overridepublic void sort(Comparator<? super E> c) {}@Overridepublic Spliterator<E> spliterator() {return singletonSpliterator(element);}}附錄:
package com.ysyc.invoicecertify.util.mockservice;import java.util.Arrays; import java.util.List;/**** 本類演示了Arrays類中的asList方法* 通過四個段落來演示,體現出了該方法的相關特性.** (1) 該方法對于基本數據類型的數組支持并不好,當數組是基本數據類型時不建議使用* (2) 當使用asList()方法時,數組就和列表鏈接在一起了.* 當更新其中之一時,另一個將自動獲得更新。* 注意:僅僅針對對象數組類型,基本數據類型數組不具備該特性* (3) asList得到的數組是的沒有add和remove方法的** 通過查看Arrays類的源碼可以知道,asList返回的List是Array中的實現的* 內部類,而該類并沒有定義add和remove方法.另外,為什么修改其中一個,另一個也自動* 獲得更新了,因為asList獲得List實際引用的就是數組*/ public class AsListTest {public static void main(String[] args) {/* 段落一:基本數據類型使用asList中的問題 *//* 說明:雖然在JDK1.6中能夠將基本數據類型的數組轉換成List,但還是有個缺陷 */int[] a_int = { 1, 2, 3, 4 };/* 預期輸出應該是1,2,3,4,但實際上輸出的僅僅是一個引用, 這里它把a_int當成了一個元素 */List a_int_List = Arrays.asList(a_int);foreach(a_int_List);/* 為此我們需要這樣遍歷其中元素 */foreachForBase(a_int_List);System.out.println("1 END 2 START");/* 段落二:對象類型的數組使用asList,是我們預期的 */Integer[] a_Integer = new Integer[] { 1, 2, 3, 4 };List a_Integer_List = Arrays.asList(a_Integer);foreach(a_Integer_List);System.out.println("2 END 3 START");/* 段落三:當更新數組或者asList之后的List,另一個將自動獲得更新 */a_Integer_List.set(0, 0);foreach(a_Integer_List);foreach(a_Integer);System.out.println("3 END 4 START");a_Integer[0] = 5;foreach(a_Integer_List);foreach(a_Integer);/* 段落四:對基本類型數組,通過asList之后的List修改對應的值后,在運行時會報出異常* 但是基本類型數組對應的List是會發生變化的,這是毫無疑問的*/a_int_List.set(0, 0);foreach(a_int_List);foreach(a_int);System.out.println("4 END 5 START");a_int[0] = 5;foreachForBase(a_int_List);foreach(a_int);}/* 打印方法 */private static void foreach(List list) {for (Object object : list) {System.out.print(object + " ");}System.out.println();}private static void foreachForBase(List a_int_List) {int[] _a_int = (int[]) a_int_List.get(0);foreach(_a_int);}private static void foreach(int[] a_int) {for (int i : a_int) {System.out.print(i + " ");}System.out.println();}private static void foreach(Integer[] _a_Integer) {for (int i : _a_Integer) {System.out.print(i + " ");}System.out.println();} }結果:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integerat java.util.Arrays$ArrayList.set(Arrays.java:3847)at com.ysyc.invoicecertify.util.mockservice.AsListTest.main(AsListTest.java:56) [I@762efe5d 1 2 3 4 1 END 2 START 1 2 3 4 2 END 3 START 0 2 3 4 0 2 3 4 3 END 4 START 5 2 3 4 5 2 3 4 Disconnected from the target VM, address: '127.0.0.1:54490', transport: 'socket'Process finished with exit code 1Collections.singletonList方法的使用
方法注釋
/*** 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*/應用
這個方法主要用于只有一個元素的優化,減少內存分配,無需分配額外的內存,可以從SingletonList內部類看得出來,由于只有一個element,因此可以做到內存分配最小化,相比之下ArrayList的DEFAULT_CAPACITY=10個。
//SingletonList類的源碼private static class SingletonList<E>extends AbstractList<E>implements RandomAccess, Serializable {private static final long serialVersionUID = 3093736618740652951L;private final E element;SingletonList(E obj) {element = obj;}public Iterator<E> iterator() {return singletonIterator(element);}public int size() {return 1;}public boolean contains(Object obj) {return eq(obj, element);}public E get(int index) {if (index != 0)throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");return element;}// Override default methods for Collection@Overridepublic void forEach(Consumer<? super E> action) {action.accept(element);}@Overridepublic boolean removeIf(Predicate<? super E> filter) {throw new UnsupportedOperationException();}@Overridepublic void replaceAll(UnaryOperator<E> operator) {throw new UnsupportedOperationException();}@Overridepublic void sort(Comparator<? super E> c) {}@Overridepublic Spliterator<E> spliterator() {return singletonSpliterator(element);}} //普通寫法List<MyBean> beans= MyService.getInstance().queryBean(param);if (CollectionUtils.isEmpty(beans)) {beans= new ArrayList<>();MyBean bean= new MyBean(param);beans.add(bean);} //優化寫法List<MyBean> beans= MyService.getInstance().queryBean(param);if (CollectionUtils.isEmpty(beans)) {MyBean bean= new MyBean(param);beans= Collections.singletonList(bean);}其他特殊容器類
public static <T> Set<T> singleton(T o);public static <T> List<T> singletonList(T o);public static <K,V> Map<K,V> singletonMap(K key, V value);// 或者直接調用常量 EMPTY_LIST public static final <T> List<T> emptyList();//或者直接調用常量 EMPTY_MAP public static final <K,V> Map<K,V> emptyMap();//或者直接調用常量 EMPTY_SET public static final <T> Set<T> emptySet()- 需要注意的是,以上6個方法返回的容器類均是immutable,即只讀的,如果調用修改接口,將會拋出UnsupportedOperationException
Collections.singletonList返回只有一個元素的不可變的List,以及其他狀態的特殊集合
Collections.singletonList,返回只有一個元素的集合,省內存,因為默認的List在JDK1.8之后初始化后add元素之后的size=10
總結
以上是生活随笔為你收集整理的Arrays.asList()和Collections.singletonList()比较的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 课程直播|极致AI助力新经济时代个性化精
- 下一篇: 范式青春er,寻找同行的你!