zoukankan      html  css  js  c++  java
  • Java中Collections的emptyList、EMPTY_LIST详解

    原创:https://mingyang.blog.csdn.net/

          在写方法的时候可能结果集不存在,需要返回null,在调用这个方法的地方就要做一个null判断,很繁琐,容易出问题,这个时候就可以使用emptyList或EMPTY_LIST。但是也会有同学说我new ArrayList不就可以了,这样是可以,但是每次我们new 一个集合对象的时候都会有一个初始化空间,占用内存资源,积少成多会浪费很多的资源,Collections中的空集合对象是一个静态常量,在内存中只存在一份,所以能够节省内存资源。

    注意:
    我们在使用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;}
    • 1

    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,他们的使用方法跟上面的大同小异。

    如果有用还请打个赏 ᕦ(・ㅂ・)ᕤ

  • 相关阅读:
    26 playbooke(二)
    25 playbook(一)
    23 ansible模块2
    23 ansible模块(一)
    22 Ansible相关工具、ansible、ansible-vault、ansible-console、ansible-galaxy
    21 Ansible安装与主机清单的编写
    Druid.jar包
    Servlet--request
    mysql-myini配置
    global,tornado的write_error,tornado的中间件的写法
  • 原文地址:https://www.cnblogs.com/yangsanluo/p/14292697.html
Copyright © 2011-2022 走看看