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的场景。在这种情况下,直接直接采用 return Collections.emptyList(); 代替 new ArrayList<XXXError>(),将不需要每次都创建一个新的实例,分配新的空间。

下面添加几个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();
    }


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

查看更多 http://www.wangmengjun.com/

你可能感兴趣的:(java,Collections,emptyList,emptyMap)