Collections.emptyXXX方法

从JDK 1.5开始, Collections集合工具类中预先定义了一些空集合:


    public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}


    public static final <K,V> Map<K,V> emptyMap() {
return (Map<K,V>) EMPTY_MAP;
}


使用这些empty方法,可以使代码的可读性变得更好,假设有一个查询方法

public ResultSet query(String tableName, Map<String, Object> queryParams){
}


如果没有任何查询参数,在调用方法query时,我们可以直接用Collections.emptyMap(); 作为参数传递。一下子可以知道没有查询参数。而且没有产生NullPointerException的风险。

同时可以提高某些场景的性能和效率,比如下面这个场景:
验证用户在页面输入的数据,并将所有的错误信息显示在页面上( 需要返回一个List对象)。 如果用户输入的数据都是正确的话,我们可能采用new ArrayList<XXXError>()去处理没有error的场景。在这种情况下,直接直接采用[color=blue]return Collections.emptyList();[/color] 代替[color=orange]new ArrayList<XXXError>()[/color],将不需要每次都创建一个新的实例,分配新的空间。

下面添加几个JDK源码中使用emptyXXX方法的例子:

/**
* Returns the list of ObjectNames of MBeans expected to be unregistered
* due to a relation removal (only for relation removal).
*
* @return a {@link List} of {@link ObjectName}.
*/
public List<ObjectName> getMBeansToUnregister() {
List<ObjectName> result;
if (unregisterMBeanList != null) {
result = new ArrayList<ObjectName>(unregisterMBeanList);
} else {
result = Collections.emptyList();
}
return result;
}


ForkJoinPool.java

/**
* Attempts to cancel and/or stop all tasks, and reject all
* subsequently submitted tasks. Tasks that are in the process of
* being submitted or executed concurrently during the course of
* this method may or may not be rejected. This method cancels
* both existing and unexecuted tasks, in order to permit
* termination in the presence of task dependencies. So the method
* always returns an empty list (unlike the case for some other
* Executors).
*
* @return an empty list
* @throws SecurityException if a security manager exists and
* the caller is not permitted to modify threads
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")}
*/
public List<Runnable> shutdownNow() {
checkPermission();
shutdown = true;
tryTerminate(true);
return Collections.emptyList();
}


原文链接[url]http://www.wangmengjun.com/showArticleDetail.do?articleId=37[/url]

查看更多[url]http://www.wangmengjun.com/[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值