ArrayList 源码解读

ArrayList 源码解读     基于JDk 1.7.0_80

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

ArrayList的底层是使用数组实现的,因为数组的容量是固定的,要实现可变容量List,所以一定存在着容量检测,数组复制等方法。

对象属性

    /**
     * 默认大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空对象数组 ,用来做比较
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 存储数据的数组
     */
    private transient Object[] elementData;

    /**
     * 大小
     */
    private int size;

构造方法

  /**
     * 指定大小*/
    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);
    }

add 方法

  public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    // 在指定位置添加对象
    public void add(int index, E element) {
        // 判断添加的位置是否合理
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                size - index);
        elementData[index] = element;
        size++;
    }
    //判断是否是空数组
    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;
        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);
    }

remove 方法

    /**
     * Removes the element at the specified position in this list.
     */
    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);
       //最后一位设为null
        elementData[--size] = null; // clear to let GC do its work
        return oldValue;
    }

    /**
     * Removes the first occurrence of the specified element from this list,
     */
    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;
    }

    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
    }

   private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }            

get方法

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

        return elementData(index);
    }

set方法

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

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

内部类Itr 实现了Iterator接口  ,实现了 next()   hasNext()  remove() 三个方法

public Iterator<E> iterator() {    return new Itr();}

/** * 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];    }

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();        }    }   //当你在使用迭代器时,不能使用 使用 set add 等方法,改变 存储的数据    final void checkForComodification() {        if (modCount != expectedModCount)            throw new ConcurrentModificationException();    }}

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();
            }
        }
    }
时间: 2024-07-29 18:43:20

ArrayList 源码解读的相关文章

Java之ArrayList源码解读(JDK 1.8)

java.util.ArrayList 详细注释了ArrayList的实现,基于JDK 1.8 . 迭代器SubList部分未详细解释,会放到其他源码解读里面.此处重点关注ArrayList本身实现. 没有采用标准的注释,并适当调整了代码的缩进以方便介绍 import java.util.AbstractList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.

ArrayList源码解读(jdk1.8)

概要 上一章,我们学习了Collection的架构.这一章开始,我们对Collection的具体实现类进行讲解:首先,讲解List,而List中ArrayList又最为常用.因此,本章我们讲解ArrayList.先对ArrayList有个整体认识,再学习它的源码,最后再通过例子来学习如何使用它.内容包括:第1部分 ArrayList简介第2部分 ArrayList数据结构第3部分 ArrayList源码解析(基于JDK1.8)第4部分 ArrayList遍历方式 第1部分 ArrayList介绍

深入理解JAVA集合系列四:ArrayList源码解读

在开始本章内容之前,这里先简单介绍下List的相关内容. List的简单介绍 有序的collection,用户可以对列表中每个元素的插入位置进行精确的控制.用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素.列表通常允许重复的元素,且允许null元素的存放. ArrayList的简单介绍 JDK中这样定义ArrayList:List接口的大小可变数据的实现. 主要有以下特点: 1.有序 2.线程不安全 3.元素可以重复 4.可以存放null值 顾名思义,取名ArrayLis

小编教ArrayList源码解读

前言1)本文章的JDK版本为JDK1.8,如果你使用的是其他版本,请参考你的Java源码!2)由于作者水平有限,本文只对部分的方法进行了分析.不足之处,希望大家指出,谢谢3)如果你对Java中的数组还没有理解,可以先学习数组及其在JVM中的存储方式,可以参考下面文章Java中数组在内存中的存放原理讲解java对象数组的概述和使用 1.继承关系public class ArrayList<E> extends AbstractList<E> implements List<E&

ArrayList源码解读

在端午节这个节日里,有一个特殊的任务,我带着你一起揭开"ArrayList"的真面目.从成员变量.构造函数.主要方法三部分,对ArrayList有进一步的认识,希望能够帮助你. 一.成员变量 //默认容量 private static final int DEFAULT_CAPACITY = 10; //空数组,当调用无参数构造函数的时候默认给个空数组 private static final Object[] EMPTY_ELEMENTDATA = {}; //真正保存数据的数组 p

ArrayList源码解读(部分)

前言:他山之石,可以攻玉 (1) fastRemove(int i),内部私有方法 private void fastRemove(int index) { //ArrayList内大量使用了此变量,用来验证ArrayList对象结构是否被修改 modCount++; int numMoved = size - index - 1; //index后的元素的个数 if (numMoved > 0) //0<=index<size-1的情况 System.arraycopy(element

jdk1.8.0_45源码解读——ArrayList的实现

jdk1.8.0_45源码解读——ArrayList的实现 一.ArrayList概述 ArrayList是List接口的可变数组的实现.实现了所有可选列表操作,并允许包括 null 在内的所有元素.除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小. 每个ArrayList实例都有一个容量,该容量是指用来存储列表元素的数组的大小.它总是至少等于列表的大小.随着向ArrayList中不断添加元素,其容量也自动增长.自动增长会带来数据向新数组的重新拷贝,因此,如果可预

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

【源码阅读】Java集合 - ArrayList深度源码解读

Java 源码阅读的第一步是Collection框架源码,这也是面试基础中的基础: 针对Collection的源码阅读写一个系列的文章,从ArrayList开始第一篇. [email protected] JDK版本 JDK 1.8.0_110 概述总结 ArrayList底层是通过数组实现的:其中capacity表示底层数组的长度,而ArrayList长度由size表示: ArrayList允许存放null元素,也可以查找null所在的index, 比如indexOf(), lastIndex