`

【Java】Collections.EMPTY_LIST和Collections.emptyList()简单使用心得

    博客分类:
  • Java
阅读更多

 

1.背景
在某些情况下,我们经常需要发挥一个空的集合对象,比如说在数据查询时,并不需要发挥一个NULL或是异常,那么就可以返回一个空的集合对象。
JDK提供了两个方式来返回集合对象,那么两者有何区别呢?那就看代码吧!

2.源码解析

 

Java代码   收藏代码
  1. //EMPTY_LIST 是Collections定义的一个静态属性,是一个类变量,可以直接返回使用  
  2.  public static final List EMPTY_LIST = new EmptyList();  
  3.   
  4. //这个是emptyList的代码  
  5.  public static final <T> List<T> emptyList() {  
  6.     return (List<T>) EMPTY_LIST;  
  7.     }  

 



从上面我们可以看出,emptyList不过是对EMPTY_LIST做了一个泛型支持。这点上我们就可以很清晰的了解两者不同的使用场景了!若是不需要泛型的情况,可以直接使用Collections,反之则使用emptyList().

3.使用
对于EMPTY_LIST就不多介绍了,我们可以直接使用Collections.EMPTY_LIST。
对于Collections.emptyList()的使用有点需要注意的地方。
若是定义了一个变量来保存这个空集合的话,那么没有问题。

 

Java代码   收藏代码
  1. List<Person> emptyPersonList = Collections.emptyList(); //编译器会自动转化。  

 

若是在某个场景下需要将空对象进行赋值那么就需要如下写法

    organization.setPersonList(Collections.<Person> emptyList());

Java代码   收藏代码
  1. organization.setPersonList(Collections.<Person> emptyList());   

 


4.BTW 
虽然在源码中存在

Java代码   收藏代码
  1. public int size() {return 0;}  
  2.   
  3.  public Object get(int index) {  
  4.           throw new IndexOutOfBoundsException("Index: "+index);  
  5.  }  

 

但是对于我们无论是 
 for (int i =0 ; i < ...)还是 for (Person p : personList)都不会调用到get(int index)这个方法,可以放心使用!前一种方式我们可以很好理解,因为首先是调用了size().后者foreach的实现原理还需要考究下!

分享到:
评论
1 楼 huanglei_jay 2014-05-07  
         

相关推荐

    EurekaLog_7.5.0.0_Enterprise

    9)....Added: EMemLeaks._ReserveOutOfMemory to control reserve size of out of memory errors (default is 50 Mb) 10)..Added: "MinLeaksLimitObjs" option (EMemLeaks unit) 11)..Added: Fatal memory problem ...

    画线橡皮筋效果实现用C#源码实现

    using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace DoubleBufferDraw { public partial ...

    leon9dragon#all_blogs#061.JAVA集合框架_Arrays类和Collections类1

    1.1. Arrays 类的常用方法 1.2.1. emptyList()/emptyMap()/emptySet() 方法 1.2.7. synchroniz

    文件内容读取类

    return Collections.emptyList(); } finally { try { if (br != null) { br.close(); } if (isr != null) { isr.close(); } } catch (IOException e) { Logger.getLogger(FileUtil.class).info(e); } }...

    DotNetFtpSources

    using System.Collections; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.Win32; using System.Security.Permissions; //Afin de lire et 閏rire des donn閑s dans la ...

    SQL、Hive SQL等SQL血缘解析工具

    return Collections.emptyList(); } @Override public boolean clearMetaColumnCache() { return true; } }); // 设置通知服务 Delegate.getDelegate().setNoticeService(s-&gt;{}); // 具有子查询的sql ...

    使用Java8 Optional的正确姿势

    我们知道 Java 8 增加了一些很有用的 API, 其中一个是 ...  return Collections.emptyList();  }  那么不得不说我们的思维仍然是在原地踏步, 只是本能的认为它不过是 User 实例的包装, 这与我们之前写成

    spring-framework-reference4.1.4

    Collections ............................................................................................... 41 Null and empty string values ...............................................................

    spring-framework-reference-4.1.2

    Collections ............................................................................................... 41 Null and empty string values ...............................................................

    Microsoft.AspNet.SignalR.2.4.0 Microsoft.AspNet.SignalR.Core.2.4.0

    using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace SignalR.通讯 { public class iHub : iHubBase { public override Task OnConnected() {...

    The way to go

    go程序设计语言 Contents Preface................................................................................................................................. xix PART 1—WHY LEARN GO—GETTING ...

    [Go语言入门(含源码)] The Way to Go (with source code)

    The Way to Go,: A Thorough Introduction to the Go Programming Language 英文书籍,已Cross the wall,从Google获得书中源代码,分享一下。喜欢请购买正版。 目录如下: Contents Preface......................

    Java邮件开发Fundamentals of the JavaMail API

    His latest book is titled Java Collections from Apress . Fundamentals of the JavaMail API Page 2 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 2....

    FTP服务器 C#

    using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; namespace FtpServer { ...

    CMS.DBUtility.dll

    /// 执行Sql和Oracle滴混合事务 /// /// &lt;param name="list"&gt;SQL命令行列表 /// &lt;param name="oracleCmdSqlList"&gt;Oracle命令行列表 /// 执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务...

    Delphi7.1 Update

    * Using collections containing component references and form inheritance can result in incorrect references being stored in the dfm file.======================================================= CORE ...

    NativeXml-master

    This file contains a list of all bugfixes, additions and enhancements to NativeXml. Maintained by Nils Haeck (SimDesign BV) ! = bugfix * = enhancement + = addition Version 4.07 (03oct2012) ! ...

    robotframework-接口自动化.pdf

    接⼝的设计规范,主要包含三点: 1)要做到流程和数据的分离,通过不断抽象,消除冗余 2)测试⽤例应尽量简单易读,避免复杂逻辑 3)建⽴测试⽤例分层架构,并坚守,⾃动化测试⽤例必须⾮常健壮,避免误报 3、编写...

    python集合用法实例分析

    # sets are unordered collections of unique hashable elements # Python23 tested vegaseat 09mar2005 # Python v2.4 has sets built in import sets print List the functions within module 'sets': for funk in...

Global site tag (gtag.js) - Google Analytics