JDK源码 ArrayList

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK源码 ArrayList相关的知识,希望对你有一定的参考价值。

java.lang.Object
    java.util.AbstractCollection<E>
        java.util.AbstractList<E>
            java.util.ArrayList<E>

所有已实现的接口:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
直接已知子类:
AttributeList, RoleList, RoleUnresolvedList

1.Iterator方法

ArrayList l = new ArrayList();
Iterator iterator = l.iterator();

调用父类AbstractList的iterator()方法,得到Itr实例(AbstractList的内部类,实现了Iterator接口),利用cursor游标实现hashNext(),及next()方法

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
 
     protected AbstractList() {
     }
 
 public Iterator<E> iterator() {
     return new Itr();
     }
 
 private class Itr implements Iterator<E> {
     /**
      * Index of element to be returned by subsequent call to next.
      */
     int cursor = 0;
 
     /**
      * Index of element returned by most recent call to next or
      * previous.  Reset to -1 if this element is deleted by a call
      * to remove.
      */
     int lastRet = -1;
 
     /**
      * The modCount value that the iterator believes that the backing
      * List should have.  If this expectation is violated, the iterator
      * has detected concurrent modification.
      */
     int expectedModCount = modCount;
 
     public boolean hasNext() {
             return cursor != size();
     }
 
     public E next() {
             checkForComodification();
         try {
         E next = get(cursor);
         lastRet = cursor++;
         return next;
         } catch (IndexOutOfBoundsException e) {
         checkForComodification();
         throw new NoSuchElementException();
         }
     }
 
     public void remove() {
         if (lastRet == -1)
         throw new IllegalStateException();
             checkForComodification();
 
         try {
         AbstractList.this.remove(lastRet);
         if (lastRet < cursor)
             cursor--;
         lastRet = -1;
         expectedModCount = modCount;
         } catch (IndexOutOfBoundsException e) {
         throw new ConcurrentModificationException();
         }
     }
 
     final void checkForComodification() {
         if (modCount != expectedModCount)
         throw new ConcurrentModificationException();
     }
     }
 }

2.Add方法

//添加元素 
public boolean add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e; //elementData为缓存数组,若不设置list的初始大小,此数组默认大小为10
    return true;
    }

   //当添加的元素数量超出数组初始值时,进行扩容操作
    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);
    }
    }

 3.addAll方法

  public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
        int numNew = a.length;
    ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
    return numNew != 0;
    }

4.clear方法

    public void clear() {
        //操作次数加一
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
    }

5.clone方法

    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 static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

6.get方法

    public E get(int index) {
    RangeCheck(index);

    return (E) elementData[index];
    }

    //检测数组越界
    private void RangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);
    }

7.indexOf方法

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

8.remove方法

    public E remove(int index) {
    RangeCheck(index);

    modCount++;
    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                 numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
    }

 9.removeAll方法

    public boolean removeAll(Collection<?> c) {
    boolean modified = false;
    Iterator<?> e = iterator();
    while (e.hasNext()) {
        if (c.contains(e.next())) {
        e.remove();
        modified = true;
        }
    }
    return modified;
    }

    //contains方法调用了indexOf方法
    public boolean contains(Object o) {
    return indexOf(o) >= 0;
    }

 

 

 

以上是关于JDK源码 ArrayList的主要内容,如果未能解决你的问题,请参考以下文章

JAVA——底层源码阅读——集合ArrayList的实现底层源码分析

JDK源码ArrayList 源码分析

源码解读:ArrayList源码解析(JDK8)

深入ArrayList源码分析(JDK1.8)

JDK源码分析-ArrayList分析

JDK源码 - ArrayList