zoukankan      html  css  js  c++  java
  • Java ArrayList调用构造方法传入"容量size"不生效,如何初始化List容量size

    创建一个ArrayList对象,传入整型参数

    @Test
        public void arrayListConstructor(){
            ArrayList<Object> objects = new ArrayList<>(5);
            System.out.println(objects.size());
         // 0 }

    结果调用size方法,返回结果却是0。

    难道是真的没生效吗?

    ArrayList对象的size()方法源码:

    /**
         * Returns the number of elements in this list.
         *
         * @return the number of elements in this list
         */
        public int size() {
            return size;
        }

    直接返回的是size属性,继续看size属性的定义:

    /**
         * The size of the ArrayList (the number of elements it contains).
         *
         * @serial
         */
        private int size;

    是一个整型的变量。

    再看ArrayList构造方法的源码:

    /**
         * Constructs an empty list with the specified initial capacity.
         *
         * @param  initialCapacity  the initial capacity of the list
         * @throws IllegalArgumentException if the specified initial capacity
         *         is negative
         */
        public ArrayList(int initialCapacity) {
            if (initialCapacity > 0) {
                this.elementData = new Object[initialCapacity];
            } else if (initialCapacity == 0) {
                this.elementData = EMPTY_ELEMENTDATA;
            } else {
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            }
        }

    这个构造方法并没有对"size"属性做任何操作,虽然不代表其他地方(代理、监听等)对size进行了处理,但是ArrayList目前没有这些东西;

    因为"size"属性在构造方法里未被赋值操作,所以当调用"size()"方法时直接返回的"size"属性,实际上是int变量默认值0

    只是指定上面构造方法指定的int型参数是容纳能力capacity,并非size的大小,list初始化还是没有一个元素,即size=0

    那么如何初始化ArrayList容量呢

    @Test
        public void appointCapacity(){
            List<Object> src = new ArrayList<>();
            src.add(123);
            src.add("Luo");
            src.add(23.5);
            // 下面一行只是指定lists的容纳能力capacity,并非size的大小,list初始化还是没有一个元素,即size=0
            // List<Object> dest = new ArrayList<>(src.size()));
    
            List<Object> dest = new ArrayList<>(Arrays.asList(new Object[src.size()]));
            System.out.println(dest.size());
            // 3
    
            // 注意,源src是第二个参数,而拷贝到链表dest是第一个参数
            Collections.copy(dest, src);
    
    
            dest.forEach(System.out::println);
        }

    上面是对一个数组进行拷贝,指定初始化数组的"size":List<Object> dest = new ArrayList<>(Arrays.asList(new Object[${size}]));

  • 相关阅读:
    刷新或关闭时调用onbeforeunload
    单词换行问题
    PhpStorm提高效率的使用方法及设置
    高质量代码编写
    数组去重
    HMTL5 本地数据库
    Html5 本地存储
    php array(object) 与xml相互转换
    pwnable.kr之leg
    文件上传漏洞及其绕过
  • 原文地址:https://www.cnblogs.com/theRhyme/p/10648027.html
Copyright © 2011-2022 走看看