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

 

时间: 2024-12-14 00:22:16

JDK源码 ArrayList的相关文章

JDK源码--ArrayList浅析

先上别人的源码分析http://www.cnblogs.com/roucheng/p/jdkfenxi.html 具体需要注意的几点: 1.默认new ArrayList()时创建一个长度为0的数组.当添加新元素的时候,如果是这种方式添加的则直接将数组长度扩展到10. 2.数组为null和空数组new Object[0]的区别是:假设一个方法返回一个数组,如果它返回null,则调用方法必须先判断是否返回null,才能对放回数组进一步处理,而如果返回空数组,则无须null引用检查.鉴于此,返回数组

JDK源码-ArrayList源码

1,继承结构图: -1,ArrayList继承AbstractList抽象类,实现List.RandomAccess.Cloneable.Serializable接口. -2,查看List接口的继承关系,我们看到List接口实现了Collection接口.Collection接口是基本集合类接口.查看Collection接口的说明: /** * The root interface in the <i>collection hierarchy</i>. A collection *

JDK源码学习----ArrayList

                                                                         JDK源码学习----ArrayList 1.ArrayList简介 ArrayList是基于Object[] 数组的,也就是我们常说的动态数组.它能很方便的实现数组的增加删除等操作. public class ArrayList<E> extends AbstractList<E> implements List<E>, R

jdk源码阅读笔记之java集合框架(二)(ArrayList)

关于ArrayList的分析,会从且仅从其添加(add)与删除(remove)方法入手. ArrayList类定义: p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco } span.s1 { color: #931a68 } public class ArrayList<E> extends AbstractList<E> implements List<E> ArrayList基本属性: /** *

由JDK源码学习ArrayList

ArrayList是实现了List接口的动态数组.与java中的数组相比,它的容量能动态增长.ArrayList的三大特点: ① 底层采用数组结构 ② 有序 ③ 非同步 下面我们从ArrayList的增加元素.获取元素.删除元素三个方面来学习ArrayList. ArrayList添加元素 因为ArrayList是采用数组实现的,其源代码比较简单.首先我们来看ArrayList的add(E e).以下代码版本是jdk7. public boolean add(E e) { // 检查数组容量 e

jdk源码解读之ArrayList

直接上源码: 构造函数:     /**      * Constructs an empty list with an initial capacity of ten.      */     public ArrayList() {     this(10);     } 其实arrayList的本质是一个数据,只不过这个数组的大小可以变化.我们先来看下arraylist的数组是怎么定义的     /**      * Constructs an empty list with the sp

【jdk源码分析】ArrayList的size()==0和isEmpty()

先看结果 分析源码 [jdk源码解析]jdk8的ArrayList初始化长度为0 java的基本数据类型默认值 无参构造 size()方法 isEmpty()方法 原文地址:https://www.cnblogs.com/xiaostudy/p/10781148.html

JDK源码分析-ArrayList分析

花了两个晚上的时间研究了一下ArrayList的源码, ArrayList 继承自AbstractList 并且实现了List, RandomAccess, Cloneable, Serializable 通过实现这三个接口 就具备了他们的功能 RandomAccess 用来表明其支持快速(通常是固定时间)随机访问 Cloneable可以克隆对象 Serializable 对象序列化就是把一个对象变为二进制的数据流的一种方法,通过对象序列化可以方便地实现对象的传输和存储,Serializable

JDK源码学习系列06----Vector

                                            JDK源码学习系列06----Vector 1.Vector简介 Vector的内部是数组实现的,它和ArrayList非常相似,最大的不同就是 Vector 是线程安全(同步)的. public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.S