ArrayList

来源:互联网 发布:软件研发部部门职责 编辑:程序博客网 时间:2024/06/05 22:46

ArrayList

ArrayList是基于底层数组的实现List。故对于LinkedList,ArrayListy善于随机访问数组,插入和删除则比较慢。

ArrayList的定义

public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  • 从ArrayList<\E>可以看出它是支持泛型的,它继承自AbstractList,实现了List、RandomAccess、Cloneable、java.io.Serializable接口。

常量

private static final long serialVersionUID = 8683452581122892189L;private static final int DEFAULT_CAPACITY = 10;private static final Object[] EMPTY_ELEMENTDATA = {};private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};transient Object[] elementData; private int size;
  • serialVersionUID :Java的序列化机制是通过serialVersionUID来验证版本一致性。
  • DEFAULT_CAPACITY :数组初始容量。
  • EMPTY_ELEMENTDATA:空数组,用以区别DEFAULTCAPACITY_EMPTY_ELEMENTDATA 。
  • DEFAULTCAPACITY_EMPTY_ELEMENTDATA :空数组,无参构造器被使用。
  • size:表示数组的大小。

构造器

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);        }}public ArrayList() {        this.elementData = DEFAULTCAPACITY_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;        }    }
  • ArrayList(int initialCapacity):有参构造器,创建容量为initialCapacity的数组。
  • ArrayList() :无参构造器,elementData指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA数组(容量为0但第一次对elementData使用add()方法时,会对其扩容,扩容默认大小为10)
  • ArrayList(Collection< ? extends E> c):创建的数组所含元素与c中的顺序、大小一致。

添加

public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }public void add(int index, E element) {        rangeCheckForAdd(index);        ensureCapacityInternal(size + 1);  // Increments modCount!!        System.arraycopy(elementData, index, elementData, index + 1,                         size - index);        elementData[index] = element;        size++;}private void ensureCapacityInternal(int minCapacity) {        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);        }        ensureExplicitCapacity(minCapacity);    } private void ensureExplicitCapacity(int minCapacity) {        modCount++;        // overflow-conscious code        if (minCapacity - elementData.length > 0)            grow(minCapacity);    }private void grow(int minCapacity) {        // overflow-conscious code        int oldCapacity = elementData.length;        int newCapacity = oldCapacity + (oldCapacity >> 1);        if (newCapacity - minCapacity < 0)            newCapacity = minCapacity;        if (newCapacity - MAX_ARRAY_SIZE > 0)            newCapacity = hugeCapacity(minCapacity);        // minCapacity is usually close to size, so this is a win:        elementData = Arrays.copyOf(elementData, newCapacity);    }public boolean addAll(Collection<? extends E> c) {        Object[] a = c.toArray();        int numNew = a.length;        ensureCapacityInternal(size + numNew);  // Increments modCount        System.arraycopy(a, 0, elementData, size, numNew);        size += numNew;        return numNew != 0;    }
  • 调用add(E e)或add(int index, E element)方法,首先会调用ensureCapacityInternal(int minCapacity)方法,确保数组有空间保存新添加的数组。

  • ensureCapacityInternal(int minCapacity)方法,先判断数组elementData 是否由无参构造器创建,若是则在该数组第一次创建时把minCapacity赋值为10;

  • ensureExplicitCapacity(int minCapacity)方法,会比较最小容量minCapacity与数组实际大小。若小则说明数组有足够空间保存新值,若大则说明数组没有足够空间保存新值且需要对数组扩容即调用grow(int minCapacity)方法。

  • grow(int minCapacity)方法中newCapacity = oldCapacity + (oldCapacity >> 1);即newCapacity =1.5倍elementData.length;也就是在newCapacity - minCapacity < 0为假且不越界的情况下会把数组扩大至1.5倍elementData.length;

删除

public E remove(int index) {        rangeCheck(index);//检查是否越界        modCount++;//Fail-Fast 机制         E oldValue = elementData(index);        int numMoved = size - index - 1;//        确认边界并把index后的元素向前移一位;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);//        把数组最后一位设置为null;原本元素即在GC时被回收        elementData[--size] = null; // clear to let GC do its work        return oldValue;}public boolean remove(Object o) {        if (o == null) {            for (int index = 0; index < size; index++)                if (elementData[index] == null) {                    fastRemove(index);                    return true;                }        } else {            for (int index = 0; index < size; index++)                if (o.equals(elementData[index])) {                    fastRemove(index);                    return true;                }        }        return false;    }private void fastRemove(int index) {        modCount++;        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        elementData[--size] = null; // clear to let GC do its work    } public void clear() {        modCount++;        // clear to let GC do its work        for (int i = 0; i < size; i++)            elementData[i] = null;        size = 0;    }public boolean removeAll(Collection<?> c) {        Objects.requireNonNull(c);        return batchRemove(c, false);    }protected void removeRange(int fromIndex, int toIndex) {        modCount++;        int numMoved = size - toIndex;//        把toIndex后的元素移动到fromIndex后        System.arraycopy(elementData, toIndex, elementData, fromIndex,                         numMoved);        // clear to let GC do its work        int newSize = size - (toIndex-fromIndex);        for (int i = newSize; i < size; i++) {            elementData[i] = null;        }        size = newSize;    }    public static void arraycopy(Object srsc,//源数组        int srcPos,//源数组要复制的起始位置        Object dest,//目的数组        int destPos,//目的数组放置的起始位置        int length) //复制的长度
  • System.arraycopy()方法把srsc第srcPos后的元素复制到dest数组第destpos位置;

  • remove(int index)方法,先检查是否越界后把index后的元素向前移一位,从而完成删除功能;

  • remove(Object o)方法,先找到o元素后由于o元素下标在范围内不会造成越界,故使用fastRemove(int index)方法快速删除;
  • fastRemove(int index)方法,跳过了越界检查故remove(int index)快;
  • Clear()方法把elementData数组中每个元素设为null;GC时会适当的回收;
  • removeRange(int fromIndex, int toIndex)方法把elementData数组下标fromIndex到toIndex的元素删除,运用到了System.arraycopy()方法;

Fail-Fast机制–modCount

  • 在多线程下,由于增加、删除操作会造成线程不安全,故用modCount来保障,若modCount与expectedModCount不一致则会造成异常,从而保障数据安全;
public ListIterator<E> listIterator() {        return new ListItr(0);    }public Iterator<E> iterator() {        return new Itr();} private class Itr implements Iterator<E> {        int cursor;       // index of next element to return        int lastRet = -1; // index of last element returned; -1 if no such        int expectedModCount = modCount;        public boolean hasNext() {            return cursor != size;        }        @SuppressWarnings("unchecked")        public E next() {            checkForComodification();            int i = cursor;            if (i >= size)                throw new NoSuchElementException();            Object[] elementData = ArrayList.this.elementData;            if (i >= elementData.length)                throw new ConcurrentModificationException();            cursor = i + 1;            return (E) elementData[lastRet = i];        }        public void remove() {            if (lastRet < 0)                throw new IllegalStateException();            checkForComodification();            try {                ArrayList.this.remove(lastRet);                cursor = lastRet;                lastRet = -1;                expectedModCount = modCount;            } catch (IndexOutOfBoundsException ex) {                throw new ConcurrentModificationException();            }        } @Override        @SuppressWarnings("unchecked")        public void forEachRemaining(Consumer<? super E> consumer) {            Objects.requireNonNull(consumer);            final int size = ArrayList.this.size;            int i = cursor;            if (i >= size) {                return;            }            final Object[] elementData = ArrayList.this.elementData;            if (i >= elementData.length) {                throw new ConcurrentModificationException();            }            while (i != size && modCount == expectedModCount) {                consumer.accept((E) elementData[i++]);            }            // update once at end of iteration to reduce heap write traffic            cursor = i;            lastRet = i - 1;            checkForComodification();        }        final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }    }
原创粉丝点击