学习过程:阅读ArrayList源码

前言

参考大佬:921天,从小厂到入职阿里

JDK1.8 中 ArrayList 的源码有1400多行(注释估计占了一半),但是我们不需要全部看,我们只需要看其中重要的内容:基础属性、构造方法、get 方法、set 方法、add 方法、remove 方法、扩容方法等。

这篇文章是自己阅读源码的一个记录。如果能成为你的参考也是意外,最重要的还是自己去阅读源码,每人的体验与收获是不同的。

正文

类的注释

阅读类的注释可以得出以下几个要点:

  • 大小可变、允许所有类型的元素(包括null)、有方法可操作已用的数组

  • 方法:size、isEmpty、get、set、iterator、listIterator、add时间复杂度为O(1)

  • ArrayList里有一个capacity实例存储元素,可自动扩容

  • ensureCapacity方法可在添加大量元素之前扩大ArrayList的capacity(容量),从而减少扩容次数

  • 不同步(非线程安全)、 提供方法:List list = Collections.synchronizedList(new ArrayList(…))

  • 通过iterators(迭代器)遍历ArrayList时不是通过迭代器的remove、add方法修改,迭代器抛出ConcurrentModificationException异常。

  • 是Java Collection集合家族中的一员。

基础属性

//  默认容量大小:10
private static final int DEFAULT_CAPACITY = 10;
//  空实例的数组
private static final Object[] EMPTY_ELEMENTDATA = {};
//  空实例的默认大小数组;与EMPTY_ELEMENTDATA区别是添加第一个元素时要扩容的大小
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//  存储ArrayList 元素的数组缓冲区;ArrayList容量即数组大小
//  elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA添加第一个元素扩容到DEFAULT_CAPACITY大小
transient Object[] elementData; // non-private to simplify nested class access
//  当前ArrayList中存储元素个数记录
private int size;

注意:
EMPTY_ELEMENTDATADEFAULTCAPACITY_EMPTY_ELEMENTDATAfinal类型,决定它们并不能存储元素,只是一个标识。

构造方法

1. 构造带有初始化容量大小的空list

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

initialCapacity:要初始化容量的值;非负数

2. 空构造

public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

3. 带有初始值构造函数

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

c : 是实现Collection接口的类。

c.toArray()可能返回的并不是Object[],所以需要特殊处理一下。

注:

1、<? extends E>: 表示任意类、E表示泛型;

是传入参数c中集合元素的类型,E是ArrayList规定的类型,即c集合元素的类型要是ArrayList中元素类型的本身或子类。

//  a中的元素时Integer类型,而c中的元素是Object类型;
//  Object extends Integer : 显然是错误的
LinkedList<Object> c = new LinkedList<>();
ArrayList<Integer> a = new ArrayList<>(c);

2、Arrays.copyOf()数组拷贝

扩容方法

ArrayList中几乎是最最重要的一个要点,所以我先看了它。

/**
  对外提供的方法。
  作用:确保ArrayList存储元素的数组大小要大于所需的最小容量。
  minCapacity:ArrayList存储元素的数组所需要的最小容量。
*/
public void ensureCapacity(int minCapacity) {
    int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
    //  所需最小容量大于minExpand,扩容。【这里minExpand为0难以理解,可能需要思考一下这个方法用在何处】
    if (minCapacity > minExpand) {
        ensureExplicitCapacity(minCapacity);
    }
}
  
/**
  数组扩容方法,用于类的内部;也是add()方法中使用的。
*/
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;  //  见名知意
    // minCapacity:ArrayList需要存储元素的最小容量, 
    // elementData.length:ArrayList存储元素的数组当前的长度
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);  //  扩容
}

/**
  具体的扩容方法
*/
private void grow(int minCapacity) {
    // 原来的容量大小
    int oldCapacity = elementData.length;
    // >>: 右移, 右移一位等于除以2;所以容量大小为原来的1.5倍。
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    // 新的容量大小 < 所需的最小容量,替换赋值
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    // 属性:MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    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);
}
/**
  minCapacity超过最大可分配值情况的处理
*/
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

提醒:ArrayList中存储元素的是数据结构是数组,所以基本上,下面的方法你自己基本上都能实现。

get 方法

@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}
//  get方法
public E get(int index) {
    rangeCheck(index);
    return elementData(index);
}  
//  索引超出当前所存元素的最大长度校验
private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

set 方法

public E set(int index, E element) {
    rangeCheck(index);

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

add 方法

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    // 按序插在最后
    elementData[size++] = e;
    return true;
}
/**
  主要看一下index后的元素的移动是怎么实现的
*/
public void add(int index, E element) {
    //  见文知意,根据get中的校验就可以想到其实现方式
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}
  
/**
  实质就是ensureExplicitCapacity这个方法。
*/
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    //  这个方法是不是有点眼熟呢?
    ensureExplicitCapacity(minCapacity);
}

注: System.arraycopy()不止一次出现,如果尚未了解,可以提前了解一下其是怎么使用与实现的。

remove 方法

/**
  删除动作即赋null,剩下交给GC  
*/
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; // clear to let GC do its work
    return oldValue;
}
  
/**
  根据元素删除,从0开始遍历,删除第一个为o的元素;
*/
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;
}

removeAll()方法

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

迭代器

在看ArrayList有关迭代器的方法前,先看一下其有关迭代器的内部类。

/**
 * An optimized version of AbstractList.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];
    }
    
    //  最终还是使用ArrayList的remove方法删除元素,但是删除后更新了expectedModCount值
    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();
    }
  
    //  禁止在使用迭代器遍历ArrayList时修改ArrayList。
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
/**
* An optimized version of AbstractList.ListItr
*/
private class ListItr extends Itr implements ListIterator<E> {
  ListItr(int index) {
      super();
      cursor = index;
  }

  public boolean hasPrevious() {
      return cursor != 0;
  }

  public int nextIndex() {
      return cursor;
  }

  public int previousIndex() {
      return cursor - 1;
  }

  @SuppressWarnings("unchecked")
  public E previous() {
      checkForComodification();
      int i = cursor - 1;
      if (i < 0)
          throw new NoSuchElementException();
      Object[] elementData = ArrayList.this.elementData;
      if (i >= elementData.length)
          throw new ConcurrentModificationException();
      cursor = i;
      return (E) elementData[lastRet = i];
  }

  public void set(E e) {
      if (lastRet < 0)
          throw new IllegalStateException();
      checkForComodification();

      try {
          ArrayList.this.set(lastRet, e);
      } catch (IndexOutOfBoundsException ex) {
          throw new ConcurrentModificationException();
      }
  }

  public void add(E e) {
      checkForComodification();

      try {
          int i = cursor;
          ArrayList.this.add(i, e);
          cursor = i + 1;
          lastRet = -1;
          expectedModCount = modCount;
      } catch (IndexOutOfBoundsException ex) {
          throw new ConcurrentModificationException();
      }
  }
}

ArrayList中有关迭代器方法

public ListIterator<E> listIterator(int index) {
    if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: "+index);
    return new ListItr(index);
}

public ListIterator<E> listIterator() {
    return new ListItr(0);
} 
public Iterator<E> iterator() {
    return new Itr();
}

其他方法

trimToSize(): 将ArrayList的elementData缩小到所存元素的大小。
size():见文知意。
isEmpty():return size == 0
contains(Object o):return indexOf(o) >= 0
indexOf(Object o)

//  for遍历,从0开始,所以返回的是第一个在elementData中出现为o的下标
public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;阅读过程中产生的问题:
1ArrayList()构造函数的执行

    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

lastIndexOf(Object o ):可以根据indexOf实现猜一下它的实现方式。
toArray():return Arrays.copyOf(elementData, size)
clear():还原到出厂状态 -

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值