Collections.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
        @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);
        }
    }
//普通寫法
    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
  • 原文鏈接:https://www.cnblogs.com/oreo/p/9761940.html


免責聲明!

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



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