Java源码分析——ArrayList

作者: 微辣鸡米饭 | 来源:发表于2017-08-25 12:49 被阅读146次

    之前已经分析了HashMap的源码,知道HashMap的内部数据结构是数组+链表+红黑树。相对于HashMap,ArrayList的内部实现方法和操作都简单的多。之前在看《Thinking In Java》的时候已经知道:ArrayList内部是用数组实现的,所以对于随机查询,效率会很高。但是对于在数组中间插入数据,和删除中间元素时,会导致后续元素的移动。

    jkd源码版本为1.8.0_05

    类的结构

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

    继承了AbstractList抽象类,其中实现了List需要的绝大多数公共方法。实现List, Cloneable, Serializable接口。还有一个RandomAccess接口,这是一个空的接口,代表这个类支持快速随机访问。

    构造函数

    //使用一个指定的初始化容量构造ArrayList
    public ArrayList(int initialCapacity) {
      super();
      if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
      this.elementData = new Object[initialCapacity];
    }
    //初始化一个空数组
    public ArrayList() {
      super();
      this.elementData = EMPTY_ELEMENTDATA;
    }
    //接受一个Collection类型的参数,转化为数组之后进行复制
    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);
    }
    

    成员字段

    //初始化的默认容量
    private static final int DEFAULT_CAPACITY = 10;
    //共享空数组
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //ArrayList中的元素数组
    transient Object[] elementData; // non-private to simplify nested class access
    //ArrayList中含有元素的个数
    private int size;
    

    这里对“共享空数组” Shared empty array instance 不是很理解。

    关键方法

    添加—add()
    /**
     * 将特定的元素添加到数组的尾部
     */
    public boolean add(E e) {
      //检查空间大小
      ensureCapacityInternal(size + 1);  // Increments modCount!!
      elementData[size++] = e;
      return true;
    }
    
    private void ensureCapacityInternal(int minCapacity) {
      //如果当前的数据元素是空数组,那么需要的容量和默认容量的最大值作为需要的容量
      if (elementData == 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;
      //扩容1.5倍
      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 void add(int index, E element) {
      //针对与添加元素,检查是否越界。
      rangeCheckForAdd(index);
      //检查是否需要扩容
      ensureCapacityInternal(size + 1);  // Increments modCount!!
      //将index---size的元素,拷贝到index+1---size+1的位置上
      System.arraycopy(elementData, index, elementData, index + 1,size - index);
      //插入数据
      elementData[index] = element;
      size++;
    }
    private void rangeCheckForAdd(int index) {
      if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    
    删除—remove()
    //删除指定位置的元素,将右边的所有元素左移一位。
    public E remove(int index) {
      //index不能超过size
      rangeCheck(index);
    
      modCount++;
      E oldValue = elementData(index);
      //需要移动的元素个数
      int numMoved = size - index - 1;
      if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,numMoved);
      //复制之后将size--,然后把最后一位赋值null
      elementData[--size] = null; // clear to let GC do its work
    
      return oldValue;
    }
    
    private void rangeCheck(int index) {
      if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    
    public boolean remove(Object o) {
      if (o == null) {
        //遍历,删除第一个为null的元素
        for (int index = 0; index < size; index++)
          if (elementData[index] == null) {
            fastRemove(index);
            return true;
          }
      } else {
        //遍历,删除第一个和o相等的元素,用equals来判断
        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
    }
    
    

    相关文章

      网友评论

      • 39b257be9915:谢谢楼主,收获颇丰
      • 金戈大王:请问为什么数组成员加了transient关键字?
        微辣鸡米饭:@金戈大王 writeObject()和readObject()是序列化和和反序列化的两个方法,有空我在文章里再补充一些吧。
        金戈大王: @微辣鸡米饭 它自己的序列化的方法是指什么?
        微辣鸡米饭:@金戈大王 ArrayList有他自己的序列化的方法,所以就不用再重复的将数组序列化了。毕竟数组里有很多空成员,全部序列化很浪费空间。

      本文标题:Java源码分析——ArrayList

      本文链接:https://www.haomeiwen.com/subject/rceudxtx.html