Java Collections的emptyList、EMPTY_LIST详解与使用说明

2022-01-24 0 831
目录

Collections的emptyList、EMPTY_LIST使用

今天在看大佬写的代码的时候,结果集为空的情况,他返回的不是null,而是:

return Collections.EMPTY_LIST;

我们都知道返回null,很有可能造成空指针异常,可以使用emptyList或EMPTY_LIST就可以避免这个问题,除非你想捕获这个为空的信息

我们在使用emptyList空的方法返回空集合的时候要注意,这个空集合是不可变的。

空的集合不可以使用add方法,会报UnsupportedOperationException异常,看如下源码:

    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

空集合对象不可以使用put方法,会报IndexOutOfBoundsException异常,看如下源码:

 public E get(int index) {
            throw new IndexOutOfBoundsException("Index: "+index);
        }

但是对于for循环都不会发生异常,如下的示例:

 List<String> list1 = Collections.emptyList();
        for(String s:list1) {
        }
        for(int i=0;i<list1.size();i++) {
        }

上面的两种for循环都可以正常的执行,第一种foreach循环,实际编译之后会变成迭代器的模式,这样我们就好理解为什么可以正常执行;第二种是只调用了size方法,我们可以看到源码直接返回0;

public int size() {return 0;}

emptyList和EMPTY_LIST的区别,我们看下源码:

    /**
     * The empty list (immutable).  This list is serializable.
     *
     * @see #emptyList()
     */
    @SuppressWarnings("unchecked")
    public static final List EMPTY_LIST = new 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&lt;String&gt; 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;
    }

我们看到EMPTY_LIST 是Collections类的一个静态常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。

通过上面的分析我们可以很清楚的知道什么时候使用emptyList;Collections集合中还有其它的几种空集合emptyMap、emptySet,他们的使用方法跟上面的大同小异。

Collections.emptyList()使用注意

偶然发现有小伙伴错误地使用了Collections.emptyList()方法,这里记录一下。它的使用方式是:

public void run() {
    ......
    List list = buildList(param);
    ......
    Object newNode = getNode(...);
    list.add(newNode);
    ......
}
 
public List buildList(Object param) {
    if (isInValid(param)) {
        return Collections.emptyList();
    } else {
        ......
    }
}

buildList方法中可能会返回一个"空的List",后续还可能往这个List添加元素(或者移除元素),但是没有注意Collections.emptyList方法返回的是一个EMPTY_LIST:

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

它是一个static final修饰的成员变量,是一个EmptyList类的实例:

public static final List EMPTY_LIST = new EmptyList<>();

这个EmptyList是一个静态内部类,和ArrayList一样继承自AbstractList:

private static class EmptyList<E>
        extends AbstractList<E>
        implements RandomAccess, Serializable {
        private static final long serialVersionUID = 8842843931221139166L; 
        public Iterator<E> iterator() {
            return emptyIterator();
        }
        public ListIterator<E> listIterator() {
            return emptyListIterator();
        }
 
        public int size() {return 0;}
        public boolean isEmpty() {return true;} 
        public boolean contains(Object obj) {return false;}
        public boolean containsAll(Collection<?> c) { return c.isEmpty(); } 
        public Object[] toArray() { return new Object[0]; } 
        public <T> T[] toArray(T[] a) {
            if (a.length > 0)
                a[0] = null;
            return a;
        }
 
        public E get(int index) {
            throw new IndexOutOfBoundsException("Index: "+index);
        }
 
        public boolean equals(Object o) {
            return (o instanceof List) && ((List<?>)o).isEmpty();
        }
 
        public int hashCode() { return 1; }
 
        // Preserves singleton property
        private Object readResolve() {
            return EMPTY_LIST;
        }
    }

可以看到这个EmptList没有重写add方法,并且get方法也是直接抛出一个IndexOutOfBoundsException异常。既然没有重写add方法,那么看看父类AbstractList中的add方法:

public boolean add(E e) {
    add(size(), e);
    return true;
}
 
public void add(int index, E element) {
    throw new UnsupportedOperationException();
}

可以看到直接抛出的UnsupportedOperationException异常。再回到EmptyList类中,它对外提供的一些方法也很明显地限制了它的使用范围。

对于Collections.emptyList(),或者说Collections.EMPTY_LIST,最好只把它当做一个空列表的标识(可以想象成一个frozen过的空List),不要对其做一些增删改查的操作。如果程序中的一些分支逻辑返回了这种实例,测试的时候又没有覆盖到,在生产环境如果走到了这个分支逻辑,那就麻烦了~

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 Java Collections的emptyList、EMPTY_LIST详解与使用说明 https://www.20zxx.cn/297612/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务