ArrayList

1. 成员变量和静态变量

 private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默认驻足大小为10.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空数组
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 默认空数组
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 基础数据存储的数组,类型transient 的作用????
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * 当前数组的大小
     */
    private int size;

2. 构造方法

    /**
     * 传入初始化大小的构造
     */
    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);
        }
    }

    /**
     * 构造空数组,默认大小为10
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 传入其他集合的构造方法,其中使用了Arrays.copyOf方法进行集合的复制
     */
    public ArrayList(Collection 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;
        }
    }

3. 增删改查方法

  • 添加
 /**
     *  向list的末尾添加数据
     */
    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);  //将所有index之后的数据都向后挪一位
        elementData[index] = element;
        size++;
    }
    /**
     * 查询下表是否越界
     */
   private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }


    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);  //扩容成运来的1.5倍
        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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
  • 删除
 /**
     * 删除第n个数值
     */
    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);  //向前移动index之后的数据
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

    /**
     *删除某个数值 
     */
    public boolean remove(Object o) {
        if (o == null) {  //从这里可以看得出来Arraylist可以存储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;
    }

    /*
     *这个私有的方法和remove方法不同有两点:1.没有检查下标 2.没有返回老的数值 
     */
    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
    }
  • 修改和获取
   /**
     * 获取第index个字段
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    /**
     * 更新字段,返回老子段
     */
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

4. fast-fail机制

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

 final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

5.序列化

基于数组实现,保存元素的数组使用 transient 修饰,该关键字声明数组默认不会被序列化。ArrayList 具有动态扩容特性,因此保存元素的数组不一定都会被使用,那么就没必要全部进行序列化。ArrayList 重写了 writeObject() 和 readObject() 来控制只序列化数组中有元素填充那部分内容。

 private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i

总结

  1. 基础结构为默认大小为10的数组,每次扩容都是原来的1.5倍(向下取整)
  2. 线程不安全
  3. 每次循环都会检查modCount是否改变,改变就直接停止循环
  4. 重写了readObject和writeObject方法,可以更好的序列化

你可能感兴趣的:(ArrayList)