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 @Override public void forEach(Consumer<? super E> action) { action.accept(element); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public void replaceAll(UnaryOperator<E> operator) { throw new UnsupportedOperationException(); } @Override public void sort(Comparator<? super E> c) { } @Override public Spliterator<E> spliterator() { return singletonSpliterator(element); } }