Java Collections.EMPTY_LIST 和 Collections.emptyList()的区别

转自:https://blog.csdn.net/liyuming0000/article/details/49474659
Collections.EMPTY_LIST返回的是一个空的List。为什么需要空的List呢?有时候我们在函数中需要返回一个List,但是这个List是空的,如果我们直接返回null的话,调用者还需要进行null的判断,所以一般建议返回一个空的List。Collections.EMPTY_LIST返回的这个空的List是不能进行添加元素这类操作的。这时候你有可能会说,我直接返回一个new ArrayList()呗,但是new ArrayList()在初始化时会占用一定的资源,所以在这种场景下,还是建议返回Collections.EMPTY_LIST。

Collections. emptyList()返回的也是一个空的List,它与Collections.EMPTY_LIST的唯一区别是,Collections. emptyList()支持泛型,所以在需要泛型的时候,可以使用Collections. emptyList()。

Collections.EMPTY_MAP和Collections.EMPTY_SET同理。

Collections.EMPTY_LIST的实现代码:

/** 
 * The empty list (immutable).  This list is serializable. 
 * 
 * @see #emptyList() 
 */  
@SuppressWarnings("unchecked")  
public static final List EMPTY_LIST = new EmptyList<>();  

Collections. emptyList()的实现代码:

/** 
 * Returns the empty list (immutable).  This list is serializable. 
 * 
 * <p>This example illustrates the type-safe way to obtain an empty list: 
 * <pre> 
 *     List<String> s = Collections.emptyList(); 
 * </pre> 
 * Implementation note:  Implementations of this method need not 
 * create a separate <tt>List</tt> object for each call.   Using this 
 * method is likely to have comparable cost to using the like-named 
 * field.  (Unlike this method, the field does not provide type safety.) 
 * 
 * @see #EMPTY_LIST 
 * @since 1.5 
 */  
@SuppressWarnings("unchecked")  
public static final <T> List<T> emptyList() {  
    return (List<T>) EMPTY_LIST;  
}  
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 对象的创建与销毁 Item 1: 使用static工厂方法,而不是构造函数创建对象:仅仅是创建对象的方法,并非Fa...
    孙小磊阅读 6,333评论 0 3
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 9,775评论 0 16
  • 在经过一次没有准备的面试后,发现自己虽然写了两年的android代码,基础知识却忘的差不多了。这是程序员的大忌,没...
    猿来如痴阅读 8,076评论 3 10
  • 看看你不读书的理由,都能出本书了 有时候我在想我们究竟为什么读书? 是为了以后可以炫耀说这本书我看过? 还是为了图...
    笔记工场阅读 2,720评论 0 0
  • 人在任何时候,都要有起航的魄力。 有这样一个故事:有一个女孩大学毕业在工作的地方认识了一个男同事。女孩无心...
    她在丛中笑哈哈阅读 1,391评论 0 1

友情链接更多精彩内容