`

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
     */

 这个方法主要用于只有一个元素的优化,减少内存分配,无需分配额外的内存。

 

 

普通写法:

 

    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

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics