ArrayList源码分析

来源:互联网 发布:帝国cms视频管理系统 编辑:程序博客网 时间:2024/09/21 06:38

ArrayList是顺序表,其实质是数组,易于查询,难于添加与删除

public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

继承AbstractList<E>
实现List<E>, RandomAccess, Cloneable, java.io.Serializable
Java中常用的三个标记接口分别是:RandomAccess、Cloneable、Serializable
java.io.Serializable这个接口是用来标记类是否支持序列化的,所谓的序列化就是将对象的各种信息转换成可以存储或者传输的一种形式。如果一个类没有实现该接口,却被拿去序列化的了,那么虚拟机就会抛出不支持序列化的异常。
Cloneable它的作用是标记该对象是否拥有克隆的能力
RandomAccess这个接口的作用是判断集合是否能快速访问,也就是通过索引下标能否快速的移动到对应的元素上

下面是2个属性

   //存储在ArrayList里的元素,以数组形式,用transient修饰保证序列化时不会被持久化    private transient Object[] elementData;   //集合的大小    private int size;

构造方法:

//创造一个空的集合,集合大小通过initialCapacity来设置public ArrayList(int initialCapacity) {    super();        if (initialCapacity < 0)            throw new IllegalArgumentException("Illegal Capacity: "+                                               initialCapacity);    this.elementData = new Object[initialCapacity];    }//调用第一个构造方法,同时设置大小为10       public ArrayList() {    this(10);    }//将其他集合加入到创建的数组中去    public ArrayList(Collection<? extends E> c) {    elementData = c.toArray();    size = elementData.length;    // c.toArray might (incorrectly) not return Object[] (see 6260652)    if (elementData.getClass() != Object[].class)        elementData = Arrays.copyOf(elementData, size, Object[].class);    }

上面第3个构造方法中用到了toArray(),这个方法的作用是将集合转化为Object类数组

//将集合的数据数组,转化为Object数组,其实是拷贝 public Object[] toArray() {        return Arrays.copyOf(elementData, size);    }  //这是讲集合的数据数组转化成你想要的类型,上面的方法只能是Object类型,而数组是无法强制转换类型的    public <T> T[] toArray(T[] a) {        if (a.length < size)            // Make a new array of a's runtime type, but my contents:            return (T[]) Arrays.copyOf(elementData, size, a.getClass());    System.arraycopy(elementData, 0, a, 0, size);        if (a.length > size)            a[size] = null;        return a;    }
  public void trimToSize() {    modCount++;    int oldCapacity = elementData.length;    if (size < oldCapacity) {            elementData = Arrays.copyOf(elementData, size);    }    }

由于elementData的长度会被拓展,size标记的是其中包含的元素的个数。所以会出现size很小但elementData.length很大的情况,将出现空间的浪费。trimToSize将返回一个新的数组给elementData,元素内容保持不变,length很size相同,节省空间。

public void ensureCapacity(int minCapacity) {    modCount++;    //得到原来预设的数组的长度    int oldCapacity = elementData.length;    //如果实际长度大于预设长度    if (minCapacity > oldCapacity) {        Object oldData[] = elementData;        //扩容        int newCapacity = (oldCapacity * 3)/2 + 1;        //如果扩容后还是小于现有数组长度            if (newCapacity < minCapacity)            //则将现有长度赋值给新的数组长度        newCapacity = minCapacity;            // minCapacity is usually close to size, so this is a win:            //生成一个新长度的元素集合数组            elementData = Arrays.copyOf(elementData, newCapacity);    }    }
  public int size() {    return size;    } public boolean isEmpty() {    return size == 0;    }

前者是计算集合大小的方法,后者是判断集合是否为空

 public boolean contains(Object o) {    return indexOf(o) >= 0;    }    public int indexOf(Object o) {    //如果查询的值为NULL    if (o == null) {    //从头开始循环对比查找,是否有值为NULL的元素,有则返回下标        for (int i = 0; i < size; i++)        if (elementData[i]==null)            return i;    //如果要查询的值不为NULL         } else {    //从头开始循环对比查找,是否有值为o的元素,有则返回下标        for (int i = 0; i < size; i++)        if (o.equals(elementData[i]))            return i;    }    //没有查找到则返回-1    return -1;    }    public int lastIndexOf(Object o) {    if (o == null) {        for (int i = size-1; i >= 0; i--)        if (elementData[i]==null)            return i;    } else {        for (int i = size-1; i >= 0; i--)        if (o.equals(elementData[i]))            return i;    }    return -1;    }

前者方法的作用是判断集合中是够包含此元素,他其实调用了后者,如得到的返回值不为-1则输出TRUE
否则输出FALSE
第3个与第2个相似,只不过它是从后往前查找,方向不一致。

   public Object clone() {    try {        ArrayList<E> v = (ArrayList<E>) super.clone();        v.elementData = Arrays.copyOf(elementData, size);        v.modCount = 0;        return v;    } catch (CloneNotSupportedException e) {        // this shouldn't happen, since we are Cloneable        throw new InternalError();    }    }

这个方法就是复制没啥好讲的

//通过下标得到相应的元素public E get(int index) {//首先检查数组下标是否越界    RangeCheck(index);    //如果不越界则返回相应的元素 数组【下标】    return (E) elementData[index];    }//通过下标在此下标设置相应的元素    public E set(int index, E element) {    //首先检查数组下标是否越界    RangeCheck(index);    //得到原来此下标下的元素    E oldValue = (E) elementData[index];    //将其替换    elementData[index] = element;    返回元素    return oldValue;    }//检查数组下标是否越界的方法 private void RangeCheck(int index) {    if (index >= size)        throw new IndexOutOfBoundsException(        "Index: "+index+", Size: "+size);    }

这是添加方法

   public boolean add(E e) {   //为防止添加元素后原数组容量不够,首先调用扩容方法    ensureCapacity(size + 1);  // Increments modCount!!    //在相应的位置添加元素    elementData[size++] = e;    //返回TRUE    return true;    }    public void add(int index, E element) {    //首先判断下标是否越界    if (index > size || index < 0)        throw new IndexOutOfBoundsException(        "Index: "+index+", Size: "+size);     //为防止添加元素后原数组容量不够,首先调用扩容方法    ensureCapacity(size+1);  // Increments modCount!!    //从数组elementData的index位置开始复制size - index个数的元素,到数组elementData的index+1的位置开始存放    System.arraycopy(elementData, index, elementData, index + 1,             size - index);    //然后在index位置插入我们要插入的数据    elementData[index] = element;    //元素个数+1    size++;    }
//通过下标移除元素  public E remove(int index) {  //检查下标是否越界    RangeCheck(index);  //操作数+1    modCount++;    //通过下标得到该位置的元素    E oldValue = (E) elementData[index];    //计算需要移动的元素的个数    int numMoved = size - index - 1;    //如果大于0,则从数组elementData的index+1位置开始的 numMoved位元素,复制到数组elementData的index位置出开始存放    if (numMoved > 0)        System.arraycopy(elementData, index+1, elementData, index,                 numMoved);  //将数组最后一位设置为NULL                   elementData[--size] = null; // Let gc do its work  //返回被删除的元素    return oldValue;    } //通过对象删除    public boolean remove(Object o) {    //如果对象为空    if (o == null) {    //从头开始找是否有元素为NULL ,有就通过index调用 fastRemove方法删除元素            for (int index = 0; index < size; index++)        if (elementData[index] == null) {            fastRemove(index);            return true;        }    } else {    //如果不为空从头开始找是否有元素为o ,有就通过index调用 fastRemove方法删除元素        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; // Let gc do its work    }
//清空集合的方法 public void clear() {    modCount++;    // Let gc do its work    //每个元素都设置为空    for (int i = 0; i < size; i++)        elementData[i] = null;   //同时把元素大小也设置为0    size = 0;    }
//向集合中添加集合的方法    public boolean addAll(Collection<? extends E> c) {    //将集合C转化成数组    Object[] a = c.toArray();    //计算出数组长度        int numNew = a.length;        //扩容    ensureCapacity(size + numNew);  // Increments modCount    //将数组a从下标为0的元素开始复制所有元素,到数组elementData,下标为size的位置开始存放        System.arraycopy(a, 0, elementData, size, numNew);        //elementData数组元素的个数扩大为,原大小加上新数组的长度        size += numNew;    return numNew != 0;    }  //将集合C从下标index处开始的元素添加到现有的数组中去    public boolean addAll(int index, Collection<? extends E> c) {    //检查下标是否越界    if (index > size || index < 0)        throw new IndexOutOfBoundsException(        "Index: " + index + ", Size: " + size);    //将集合转化为数组    Object[] a = c.toArray();    //计算出数组长度    int numNew = a.length;      //扩容    ensureCapacity(size + numNew);  // Increments modCount     //计算出需要移动的元素个数    int numMoved = size - index;    if (numMoved > 0)    //将数组elementData从下标index处开始 numMoved个元素,复制到elementData数组下标为index + numNew处开始存放        System.arraycopy(elementData, index, elementData, index + numNew,                 numMoved);//将数组a从下标为0的元素开始复制所有元素,到数组elementData,下标为index的位置开始存放        System.arraycopy(a, 0, elementData, index, numNew);         //elementData数组元素的个数扩大为,原大小加上新数组的长度    size += numNew;    return numNew != 0;    }
 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 array length        s.writeInt(elementData.length);    // Write out all elements in the proper order.    for (int i=0; i<size; i++)            s.writeObject(elementData[i]);    if (modCount != expectedModCount) {            throw new ConcurrentModificationException();        }    }    private void readObject(java.io.ObjectInputStream s)        throws java.io.IOException, ClassNotFoundException {    // Read in size, and any hidden stuff    s.defaultReadObject();        // Read in array length and allocate array        int arrayLength = s.readInt();        Object[] a = elementData = new Object[arrayLength];    // Read in all elements in the proper order.    for (int i=0; i<size; i++)            a[i] = s.readObject();    }}

elementData数组相当于容器,当容器不足时就会再扩充容量,但是容器的容量往往都是大于或者等于ArrayList所存元素的个数。
比如,现在实际有了8个元素,那么elementData数组的容量可能是8x1.5=12,如果直接序列化elementData数组,那么就会浪费4个元素的空间,特别是当元素个数非常多时,这种浪费是非常不合算的。所以ArrayList的设计者将elementData设计为transient,然后在writeObject方法中手动将其序列化,并且只序列化了实际存储的那些元素,而不是整个数组。

  protected void removeRange(int fromIndex, int toIndex) {    modCount++;    int numMoved = size - toIndex;        System.arraycopy(elementData, toIndex, elementData, fromIndex,                         numMoved);    // Let gc do its work    int newSize = size - (toIndex-fromIndex);    while (size != newSize)        elementData[--size] = null;    }

执行过程是将elementData从toIndex位置开始的元素向前移动到fromIndex,然后将toIndex位置之后的元素全部置空顺便修改size。效果与subList(int fromIndex, int toIndex).clear() 一样,其实使用subList(int fromIndex, int toIndex).clear() 就是在调用removeRange

原创粉丝点击