JDK源码分析-ArrayList分析

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

下面看看ArrayList 整体架构。
这里写图片描述

集合的顶层接口就是Collection,它继承Iterable(Iterator是一个接口,它是集合的迭代器。集合可以通过Iterator去遍历集合中的元素。Iterator提供的API接口,包括:是否存在下一个元素、获取下一个元素、删除当前元素。),Collection是高度抽象出来的集合,它包含了集合的基本操作和属性。定义了一些方法,见如下源码
看一下它的源码



package java.util;

public interface Collection<E> extends Iterable<E> {
    
    

    //返回此 collection 中的元素数
    int size();

    //如果此 collection 不包含元素,则返回 true
    boolean isEmpty();

    // 如果此 collection 包含指定的元素,则返回 true。
    boolean contains(Object o);

    //返回在此 collection 的元素上进行迭代的迭代器
    Iterator<E> iterator();

    //返回包含此 collection 中所有元素的数组
    Object[] toArray();

    //返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同
    <T> T[] toArray(T[] a);

    /**确保此 collection 包含指定的元素(可选操作)。
    *如果此 collection 由于调用而发生更改,则返回 true。
    */(如果此 collection 不允许有重复元素,并且已经包含了指定的元素,则返回 false。)
    boolean add(E e);

    //从此 collection 中移除指定元素的单个实例
    boolean remove(Object o);

    //如果此 collection 包含指定 collection 中的所有元素,则返回 true
    boolean containsAll(Collection<?> c);

    //将指定 collection 中的所有元素都添加到此 collection 中
    boolean addAll(Collection<? extends E> c);

    //移除此 collection 中那些也包含在指定 collection 中的所有元素
    boolean removeAll(Collection<?> c);

    //仅保留此 collection 中那些也包含在指定 collection 的元素
    boolean retainAll(Collection<?> c);

    //移除此 collection 中的所有元素
    void clear();

    //比较此 collection 与指定对象是否相等。 
    boolean equals(Object o); 

    //返回此 collection 的哈希码值
    int hashCode();
}

ArrayList 继承自AbstractList ,来看看AbstractList

AbstractList是一个继承于AbstractCollection,并且实现List接口的抽象类。它实现了List中除size()、get(int location)之外的函数。
AbstractList的主要作用:它实现了List接口中的大部分函数。从而方便其它类继承List。
另外,和AbstractCollection相比,AbstractList抽象类中,实现了iterator()接口。

AbstractList源码如下:


/*
 *此类提供 List 接口的骨干实现,以最大限度地减少实现“随机访问”数据存储(如数组)支持的该接口所需的工作。
 *AbstractList是一个继承于AbstractCollection,并且实现List接口的抽象类。它实现了List中除size()、get(int location)之外的函数。
 *AbstractList的主要作用:它实现了List接口中的大部分函数。从而方便其它类继承List。
 *另外,和AbstractCollection相比,AbstractList抽象类中,实现了iterator()接口。 
 */

package java.util;

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
   
   
    /**
     *唯一的构造方法。(由子类构造方法调用,通常是隐式的。) 
     */
    protected AbstractList() {
    }


    //将指定的元素添加到此列表的尾部
    public boolean add(E e) {
        add(size(), e);//调用了在指定位置添加元素的方法
        return true;
    }

    //返回列表中指定位置的元素。
    abstract public E get(int index);

    //用指定元素替换列表中指定位置的元素
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }

   //在列表的指定位置插入指定元素
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

    //移除列表中指定位置的元素
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }


   //返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。
    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex();
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }

    //返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1
    public int lastIndexOf(Object o) {
        ListIterator<E> it = listIterator(size());
        if (o==null) {
            while (it.hasPrevious())
                if (it.previous()==null)
                    return it.nextIndex();
        } else {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }


   //从此列表中移除所有元素
    public void clear() {
        removeRange(0, size());
    }

   //将指定 collection 中的所有元素都插入到列表中的指定位置
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;
    }


    //返回在此列表的元素上进行迭代的迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }

    //返回此列表元素的列表迭代器
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }

    //返回列表中元素的列表迭代器(按适当顺序),从列表的指定位置开始
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }
    //内部类
    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 {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0)
                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();
        }
    }
    //内部类
    private class ListItr extends Itr implements ListIterator<E> {
   
   
        ListItr(int index) {
            cursor = index;
        }

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

        public E previous() {
            checkForComodification();
            try {
                int i = cursor - 1;
                E previous = get(i);
                lastRet = cursor = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public int nextIndex() {
            return cursor;
        }

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

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

            try {
                AbstractList.this.set(lastRet, e);
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

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

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

    //返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。(
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }

    //将指定的对象与此列表进行相等性比较。
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof List))
            return false;

        ListIterator<E> e1 = listIterator();
        ListIterator e2 = ((List) o).listIterator();
        while (e1.hasNext() && e2.hasNext()) {
            E o1 = e1.next();
            Object o2 = e2.next();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        }
        return !(e1.hasNext() || e2.hasNext());
    }

    //返回此列表的哈希码值
    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }

    //从此列表中移除索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素
    protected void removeRange(int fromIndex, int toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }


    protected
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值