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

Collections.EMPTY_LIST返回的是一个空的List。为什么需要空的List呢?有时候我们在函数中需要返回一个List,但是这个List是空的,如果我们直接返回null的话,调用者还需要进行null的判断,所以一般建议返回一个空的List。(编者注:比如,用到list.size(),这个时候会忘记也很麻烦,再判断是否为空。不像循环,肯定会判断是否为空 。所以不要return null,return Collections.EMPTY_LIST这个比较好EMPTY_LIST的size为0)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的实现代码:

 

[java]  view plain  copy
 
  1. /** 
  2.  * The empty list (immutable).  This list is serializable. 
  3.  * 
  4.  * @see #emptyList() 
  5.  */  
  6. @SuppressWarnings("unchecked")  
  7. public static final List EMPTY_LIST = new EmptyList<>();  

Collections. emptyList()的实现代码:

 

[java]  view plain  copy
 
  1. /** 
  2.  * Returns the empty list (immutable).  This list is serializable. 
  3.  * 
  4.  * <p>This example illustrates the type-safe way to obtain an empty list: 
  5.  * <pre> 
  6.  *     List<String> s = Collections.emptyList(); 
  7.  * </pre> 
  8.  * Implementation note:  Implementations of this method need not 
  9.  * create a separate <tt>List</tt> object for each call.   Using this 
  10.  * method is likely to have comparable cost to using the like-named 
  11.  * field.  (Unlike this method, the field does not provide type safety.) 
  12.  * 
  13.  * @see #EMPTY_LIST 
  14.  * @since 1.5 
  15.  */  
  16. @SuppressWarnings("unchecked")  
  17. public static final <T> List<T> emptyList() {  
  18.     return (List<T>) EMPTY_LIST;  
  19. }  

测试代码演示:

 

[java]  view plain  copy
 
  1. import java.util.Collections;  
  2. import java.util.List;  
  3.   
  4. public class CollectionsTest {  
  5.   
  6.     public static void main(String[] args) {  
  7.         List list1 = Collections.EMPTY_LIST;  
  8.         System.out.println(list1.size());  
  9.         try {  
  10.             list1.add(1);  
  11.         } catch (Exception e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.           
  15.         List<Integer> list2 = Collections.<Integer>emptyList();  
  16.         System.out.println(list2.size());  
  17.         try {  
  18.             list2.add(1);  
  19.         } catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23. }  

测试输出:


 

 

 

REFS:http://blog.csdn.net/liyuming0000/article/details/49474659

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值