ArrayList学习笔记三(构造方法)

1.无参构造

初始化elementData为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,此时的容量为0

public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

2.带有容量的构造

如果容量(initialCapacity)大于0 ,则初始化elementData为Object类型长度为initialCapacity的数组

如果容量(initialCapacity)等于0,则初始化elementData为EMPTY_ELEMENTDATA

否则(小于0),抛出不合法参数异常

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);
        }
}

3.带有(Collection<? extends E> c)参数的构造

首席c转换为数组赋值给elementData

数组elementData的实际长度赋值给size,

如果size不等于0 代表有数据 如果c的类型不是Object 则转换为Object类型给elementData

否则(size等于0)elementData 为EMPTY_ELEMENTDATA

public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
}

 

posted @ 2020-11-24 15:44  oddPoint  阅读(166)  评论(0编辑  收藏  举报