List--ArrayList(浅识)一

来源:互联网 发布:安全员c证网络查询 编辑:程序博客网 时间:2024/06/05 14:06

java中ArrayList在平常的开发中用的是比较多的,ArrayLis是List接口的一个实现。

1)ArrayList类有三个构造方法:public ArrayList(int initialCapacity) ;创建一个ArrayList对象初始化大小;public ArrayList();无参构造方法,调用参数为int型的构造方法,默认大小为10;public ArrayList(Collection<? extends E> c);参数为一个集合,将传入的参数集合拷贝给新建的ArrayList对象。这就是ArrayList的三个构造方法,用来初始化创建的ArrayList对象

2)ArrayList采用数组存储对象分配连续空间,查找方便。ArrayList添加无素,超过默认大小时,需对存储对象的数组进行扩容,数组的扩容还是采用Arrays的copyOf方法,每次扩容为原大小的1.5倍(原因未知)。ArrayList删除元素,原码如下:

public E remove(int index) {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
        return oldValue;
    }

删除元素后,需要把下标减一。这是因为在每次删除元素后,ArrayList会将后面部分的元素依次往上挪一个位置(就是copy);

3)从原码中可以看到ArrayList的添加和删除都没同步(加锁),所以new ArrayList()创建的对象非线程安全的,当我们需要一个线程安全的ArrayList对象时,可采用Collections.synchronizedList来创建一个线程安全的ArrayList对象。

以上是对ArrayList的最基础见解,以后还需更改。

0 0