Java集合框架01-Collection架构与源码分析

原本地址:http://blog.csdn.net/eson_15/article/details/51139978 原文作者写的很好,容易理解,给源码加了自己的自己的注释

Collection是一个接口,它主要的两个分支是List和Set。如下图所示:

《Java集合框架01-Collection架构与源码分析》

List和Set都是接口,它们继承与Collection。List是有序的队列,可以用重复的元素;而Set是数学概念中的集合,不能有重复的元素。List和Set都有它们各自的实现类。

为了方便,我们抽象出AbstractCollection类来让其他类继承,该类实现类Collection中的绝大部分方法。AbstractList和AbstractSet都继承与AbstractCollection,具体的List实现类继承与AbstractList,而Set的实现类则继承与AbstractSet。

另外,Collection中有个iterator()方法,它的作用是返回一个Iterator接口。通常,我们通过Iterator迭代器来遍历集合。ListIterator是List接口所特有的,在List接口中,通过ListIterator()返回一个ListIterator对象。

我们首先来阅读下这些 接口和抽象类以及他们的实现类中都有哪些方法:

1. Collection

Collection的定义如下:

  1. public interface Collection<E> extends Iterable<E> {}
public interface Collection<E> extends Iterable<E> {}

从它的定义中可以看出,Collection是一个接口。它是一个高度抽象出来的集合,包含了集合的基本操作:添加、删除、清空、遍历、是否为空、获取大小等。

Collection接口的所有子类(直接子类和简介子类)都必须实现2种构造函数:不带参数的构造函数和参数为Collection的构造函数。带参数的构造函数可以用来转换Collection的类型。下面是Collection接口中定义的API:

  1. // Collection的API
  2. abstract boolean         add(E object)
  3. abstract boolean         addAll(Collection<? extends E> collection)
  4. abstract void            clear()
  5. abstract boolean         contains(Object object)
  6. abstract boolean         containsAll(Collection<?> collection)
  7. abstract boolean         equals(Object object)
  8. abstract int             hashCode()
  9. abstract boolean         isEmpty()
  10. abstract Iterator<E>     iterator()
  11. abstract boolean         remove(Object object)
  12. abstract boolean         removeAll(Collection<?> collection)
  13. abstract boolean         retainAll(Collection<?> collection)
  14. abstract int             size()
  15. abstract <T> T[]         toArray(T[] array)
  16. abstract Object[]        toArray()
// Collection的API
abstract boolean         add(E object)
abstract boolean         addAll(Collection<? extends E> collection)
abstract void            clear()
abstract boolean         contains(Object object)
abstract boolean         containsAll(Collection<?> collection)
abstract boolean         equals(Object object)
abstract int             hashCode()
abstract boolean         isEmpty()
abstract Iterator<E>     iterator()
abstract boolean         remove(Object object)
abstract boolean         removeAll(Collection<?> collection)
abstract boolean         retainAll(Collection<?> collection)
abstract int             size()
abstract <T> T[]         toArray(T[] array)
abstract Object[]        toArray()

2. List

List的定义如下:

  1. public interface List<E> extends Collection<E> {}
public interface List<E> extends Collection<E> {}

从List定义中可以看出,它继承与Collection接口,即List是集合的一种。List是有序的队列,List中的每一个元素都有一个索引,第一个元素的索引值为0,往后的元素的索引值依次+1.,List中允许有重复的元素。

List继承Collection自然包含了Collection的所有接口,由于List是有序队列,所以它也有自己额外的API接口。API如下:

  1. // Collection的API
  2. abstract boolean         add(E object)
  3. abstract boolean         addAll(Collection<? extends E> collection)
  4. abstract void            clear()
  5. abstract boolean         contains(Object object)
  6. abstract boolean         containsAll(Collection<?> collection)
  7. abstract boolean         equals(Object object)
  8. abstract int             hashCode()
  9. abstract boolean         isEmpty()
  10. abstract Iterator<E>     iterator()
  11. abstract boolean         remove(Object object)
  12. abstract boolean         removeAll(Collection<?> collection)
  13. abstract boolean         retainAll(Collection<?> collection)
  14. abstract int             size()
  15. abstract <T> T[]         toArray(T[] array)
  16. abstract Object[]        toArray()
  17. // 相比与Collection,List新增的API:
  18. abstract void                add(int location, E object) //在指定位置添加元素
  19. abstract boolean             addAll(int location, Collection<? extends E> collection) //在指定位置添加其他集合中的元素
  20. abstract E                   get(int location) //获取指定位置的元素
  21. abstract int                 indexOf(Object object) //获得指定元素的索引
  22. abstract int                 lastIndexOf(Object object) //从右边的索引
  23. abstract ListIterator<E>     listIterator(int location) //获得iterator
  24. abstract ListIterator<E>     listIterator()
  25. abstract E                   remove(int location) //删除指定位置的元素
  26. abstract E                   set(int location, E object) //修改指定位置的元素
  27. abstract List<E>             subList(int start, int end) //获取子list
// Collection的API
abstract boolean         add(E object)
abstract boolean         addAll(Collection<? extends E> collection)
abstract void            clear()
abstract boolean         contains(Object object)
abstract boolean         containsAll(Collection<?> collection)
abstract boolean         equals(Object object)
abstract int             hashCode()
abstract boolean         isEmpty()
abstract Iterator<E>     iterator()
abstract boolean         remove(Object object)
abstract boolean         removeAll(Collection<?> collection)
abstract boolean         retainAll(Collection<?> collection)
abstract int             size()
abstract <T> T[]         toArray(T[] array)
abstract Object[]        toArray()
// 相比与Collection,List新增的API:
abstract void                add(int location, E object) //在指定位置添加元素
abstract boolean             addAll(int location, Collection<? extends E> collection) //在指定位置添加其他集合中的元素
abstract E                   get(int location) //获取指定位置的元素
abstract int                 indexOf(Object object) //获得指定元素的索引
abstract int                 lastIndexOf(Object object) //从右边的索引
abstract ListIterator<E>     listIterator(int location) //获得iterator
abstract ListIterator<E>     listIterator()
abstract E                   remove(int location) //删除指定位置的元素
abstract E                   set(int location, E object) //修改指定位置的元素
abstract List<E>             subList(int start, int end) //获取子list

3. Set

Set的定义如下:

  1. public interface Set<E> extends Collection<E> {}
public interface Set<E> extends Collection<E> {}

Set也继承与Collection接口,且里面不能有重复元素。关于API,Set与Collection的API完全一样,不在赘述。

4. AbstractCollection

  1. public abstract class AbstractCollection<E> implements Collection<E> {}
public abstract class AbstractCollection<E> implements Collection<E> {}

AbstractCollection是一个抽象类,它实现了Collection中除了iterator()和size()之外的所有方法。AbstractCollection的主要作用是方便其他类实现Collection.,比如ArrayList、LinkedList等。它们想要实现Collection接口,通过集成AbstractCollection就已经实现大部分方法了,再实现一下iterator()和size()即可。

下面看一下AbstractCollection实现的部分方法的源码:

  1. public abstract class AbstractCollection<E> implements Collection<E> {
  2.     protected AbstractCollection() {
  3.     }
  4.     public abstract Iterator<E> iterator();//iterator()方法没有实现
  5.     public abstract int size(); //size()方法也没有实现
  6.     public boolean isEmpty() { //检测集合是否为空
  7.         return size() == 0;
  8.     }
  9.     /*检查集合中是否包含特定对象*/
  10.     public boolean contains(Object o) {
  11.         Iterator<E> it = iterator();
  12.         if (o==null) {
  13.             while (it.hasNext()) //从这里可以看出,任何非空集合都包含null
  14.                 if (it.next()==null)
  15.                     return true;
  16.         } else {
  17.             while (it.hasNext())
  18.                 if (o.equals(it.next()))
  19.                     return true;
  20.         }
  21.         return false;
  22.     }
  23.     /*将集合转变成数组*/
  24.     public Object[] toArray() {
  25.         // Estimate size of array; be prepared to see more or fewer elements
  26.         Object[] r = new Object[size()]; //创建与集合大小相同的数组
  27.         Iterator<E> it = iterator();
  28.         for (int i = 0; i < r.length; i++) {
  29.             if (! it.hasNext()) // fewer elements than expected
  30.                 //Arrays.copy(**,**)的第二个参数是待copy的长度,如果这个长度大于r,则保留r的长度
  31.                 return Arrays.copyOf(r, i);
  32.             r[i] = it.next();
  33.         }
  34.         return it.hasNext() ? finishToArray(r, it) : r;
  35.     }
  36.     public <T> T[] toArray(T[] a) {
  37.         // Estimate size of array; be prepared to see more or fewer elements
  38.         int size = size();
  39.         T[] r = a.length >= size ? a :
  40.                   (T[])java.lang.reflect.Array
  41.                   .newInstance(a.getClass().getComponentType(), size);
  42.         Iterator<E> it = iterator();
  43.         for (int i = 0; i < r.length; i++) {
  44.             if (! it.hasNext()) { // fewer elements than expected
  45.                 if (a == r) {
  46.                     r[i] = null; // null-terminate
  47.                 } else if (a.length < i) {
  48.                     return Arrays.copyOf(r, i);
  49.                 } else {
  50.                     System.arraycopy(r, 0, a, 0, i);
  51.                     if (a.length > i) {
  52.                         a[i] = null;
  53.                     }
  54.                 }
  55.                 return a;
  56.             }
  57.             r[i] = (T)it.next();
  58.         }
  59.         // more elements than expected
  60.         return it.hasNext() ? finishToArray(r, it) : r;
  61.     }
  62.     private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
  63.         int i = r.length;
  64.         while (it.hasNext()) {
  65.             int cap = r.length;
  66.             if (i == cap) {
  67.                 int newCap = cap + (cap >> 1) + 1;
  68.                 // overflow-conscious code
  69.                 if (newCap – MAX_ARRAY_SIZE > 0)
  70.                     newCap = hugeCapacity(cap + 1);
  71.                 r = Arrays.copyOf(r, newCap);
  72.             }
  73.             r[i++] = (T)it.next();
  74.         }
  75.         // trim if overallocated
  76.         return (i == r.length) ? r : Arrays.copyOf(r, i);
  77.     }
  78.     private static int hugeCapacity(int minCapacity) {
  79.         if (minCapacity < 0) // overflow
  80.             throw new OutOfMemoryError
  81.                 (”Required array size too large”);
  82.         return (minCapacity > MAX_ARRAY_SIZE) ?
  83.             Integer.MAX_VALUE :
  84.             MAX_ARRAY_SIZE;
  85.     }
  86.     // 删除对象o
  87.     public boolean remove(Object o) {
  88.         Iterator<E> it = iterator();
  89.         if (o==null) {
  90.             while (it.hasNext()) {
  91.                 if (it.next()==null) {
  92.                     it.remove();
  93.                     return true;
  94.                 }
  95.             }
  96.         } else {
  97.             while (it.hasNext()) {
  98.                 if (o.equals(it.next())) {
  99.                     it.remove();
  100.                     return true;
  101.                 }
  102.             }
  103.         }
  104.         return false;
  105.     }
  106.    <pre name=”code” class=“java”>    // 判断是否包含集合c中所有元素
  107.     public boolean containsAll(Collection<?> c) {
  108.         for (Object e : c)
  109.             if (!contains(e))
  110.                 return false;
  111.         return true;
  112.     }
  113.     //添加集合c中所有元素
  114.     public boolean addAll(Collection<? extends E> c) {
  115.         boolean modified = false;
  116.         for (E e : c)
  117.             if (add(e))
  118.                 modified = true;
  119.         return modified;
  120.     }
  121.     //删除集合c中所有元素(如果存在的话)
  122.     public boolean removeAll(Collection<?> c) {
  123.         boolean modified = false;
  124.         Iterator<?> it = iterator();
  125.         while (it.hasNext()) {
  126.             if (c.contains(it.next())) {
  127.                 it.remove();
  128.                 modified = true;
  129.             }
  130.         }
  131.         return modified;
  132.     }
  133.     //清空
  134.     public void clear() {
  135.         Iterator<E> it = iterator();
  136.         while (it.hasNext()) {
  137.             it.next();
  138.             it.remove();
  139.         }
  140.     }
  141.     //将集合元素显示成[String]
  142.     public String toString() {
  143.         Iterator<E> it = iterator();
  144.         if (! it.hasNext())
  145.             return “[]”;
  146.         StringBuilder sb = new StringBuilder();
  147.         sb.append(’[‘);
  148.         for (;;) {
  149.             E e = it.next();
  150.             sb.append(e == this ? “(this Collection)” : e);
  151.             if (! it.hasNext())
  152.                 return sb.append(‘]’).toString();
  153.             sb.append(’,’).append(‘ ’);
  154.         }
  155.     }
  156. }
public abstract class AbstractCollection<E> implements Collection<E> {
    protected AbstractCollection() {
    }

    public abstract Iterator<E> iterator();//iterator()方法没有实现

    public abstract int size(); //size()方法也没有实现

    public boolean isEmpty() { //检测集合是否为空
        return size() == 0;
    }
    /*检查集合中是否包含特定对象*/
    public boolean contains(Object o) { 
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) //从这里可以看出,任何非空集合都包含null
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }
    /*将集合转变成数组*/
    public Object[] toArray() {
        // Estimate size of array; be prepared to see more or fewer elements
        Object[] r = new Object[size()]; //创建与集合大小相同的数组
        Iterator<E> it = iterator();
        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) // fewer elements than expected
                //Arrays.copy(**,**)的第二个参数是待copy的长度,如果这个长度大于r,则保留r的长度
                return Arrays.copyOf(r, i);
            r[i] = it.next();
        }
        return it.hasNext() ? finishToArray(r, it) : r;
    }

    public <T> T[] toArray(T[] a) {
        // Estimate size of array; be prepared to see more or fewer elements
        int size = size();
        T[] r = a.length >= size ? a :
                  (T[])java.lang.reflect.Array
                  .newInstance(a.getClass().getComponentType(), size);
        Iterator<E> it = iterator();

        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) { // fewer elements than expected
                if (a == r) {
                    r[i] = null; // null-terminate
                } else if (a.length < i) {
                    return Arrays.copyOf(r, i);
                } else {
                    System.arraycopy(r, 0, a, 0, i);
                    if (a.length > i) {
                        a[i] = null;
                    }
                }
                return a;
            }
            r[i] = (T)it.next();
        }
        // more elements than expected
        return it.hasNext() ? finishToArray(r, it) : r;
    }

    private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
        int i = r.length;
        while (it.hasNext()) {
            int cap = r.length;
            if (i == cap) {
                int newCap = cap + (cap >> 1) + 1;
                // overflow-conscious code
                if (newCap - MAX_ARRAY_SIZE > 0)
                    newCap = hugeCapacity(cap + 1);
                r = Arrays.copyOf(r, newCap);
            }
            r[i++] = (T)it.next();
        }
        // trim if overallocated
        return (i == r.length) ? r : Arrays.copyOf(r, i);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError
                ("Required array size too large");
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    // 删除对象o
    public boolean remove(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) {
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }
   <pre name="code" class="java">    // 判断是否包含集合c中所有元素
    public boolean containsAll(Collection<?> c) {
        for (Object e : c)
            if (!contains(e))
                return false;
        return true;
    }

    //添加集合c中所有元素
    public boolean addAll(Collection<? extends E> c) {
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

    //删除集合c中所有元素(如果存在的话)
    public boolean removeAll(Collection<?> c) {
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

    //清空
    public void clear() {
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            it.next();
            it.remove();
        }
    }

    //将集合元素显示成[String]
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

}

5. AbstractList

AbstractList的定义如下:

  1. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {}

从定义中可以看出,AbstractList是一个继承AbstractCollection,并且实现了List接口的抽象类。它实现了List中除了size()、get(int location)之外的方法。

AbstractList的主要作用:它实现了List接口中的大部分函数,从而方便其它类继承List。另外,和AbstractCollection相比,AbstractList抽象类中,实现了iterator()方法。

AbstractList抽象类的源码如下:

  1. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
  2.     protected AbstractList() {
  3.     }
  4.     public boolean add(E e) {
  5.         add(size(), e);
  6.         return true;
  7.     }
  8.     abstract public E get(int index);
  9.     public E set(int index, E element) {
  10.         throw new UnsupportedOperationException();
  11.     }
  12.     public void add(int index, E element) {
  13.         throw new UnsupportedOperationException();
  14.     }
  15.     public E remove(int index) {
  16.         throw new UnsupportedOperationException();
  17.     }
  18. /***************************** Search Operations**********************************/
  19.     public int indexOf(Object o) { //搜索对象o的索引
  20.         ListIterator<E> it = listIterator();
  21.         if (o==null) {
  22.             while (it.hasNext())
  23.                 if (it.next()==null) //执行it.next(),会先返回it指向位置的值,然后it会移到下一个位置
  24.                     return it.previousIndex(); //所以要返回it.previousIndex(); 关于it几个方法的源码在下面
  25.         } else {
  26.             while (it.hasNext())
  27.                 if (o.equals(it.next()))
  28.                     return it.previousIndex();
  29.         }
  30.         return -1;
  31.     }
  32.     public int lastIndexOf(Object o) {
  33.         ListIterator<E> it = listIterator(size());
  34.         if (o==null) {
  35.             while (it.hasPrevious())
  36.                 if (it.previous()==null)
  37.                     return it.nextIndex();
  38.         } else {
  39.             while (it.hasPrevious())
  40.                 if (o.equals(it.previous()))
  41.                     return it.nextIndex();
  42.         }
  43.         return -1;
  44.     }
  45. /**********************************************************************************/
  46. /****************************** Bulk Operations ***********************************/
  47.     public void clear() {
  48.         removeRange(0, size());
  49.     }
  50.     public boolean addAll(int index, Collection<? extends E> c) {
  51.         rangeCheckForAdd(index);
  52.         boolean modified = false;
  53.         for (E e : c) {
  54.             add(index++, e);
  55.             modified = true;
  56.         }
  57.         return modified;
  58.     }
  59.     protected void removeRange(int fromIndex, int toIndex) {
  60.         ListIterator<E> it = listIterator(fromIndex);
  61.         for (int i=0, n=toIndex-fromIndex; i<n; i++) {
  62.             it.next();
  63.             it.remove();
  64.         }
  65.     }
  66. /**********************************************************************************/
  67. /********************************* Iterators **************************************/
  68.     public Iterator<E> iterator() {
  69.         return new Itr();
  70.     }
  71.     public ListIterator<E> listIterator() {
  72.         return listIterator(0); //返回的iterator索引从0开始
  73.     }
  74.     public ListIterator<E> listIterator(final int index) {
  75.         rangeCheckForAdd(index); //首先检查index范围是否正确
  76.         return new ListItr(index); //ListItr继承与Itr且实现了ListIterator接口,Itr实现了Iterator接口,往下看
  77.     }
  78.     private class Itr implements Iterator<E> {
  79.         int cursor = 0; //元素的索引,当调用next()方法时,返回当前索引的值
  80.         int lastRet = -1; //lastRet也是元素的索引,但如果删掉此元素,该值置为-1
  81.          /*
  82.          *迭代器都有个modCount值,在使用迭代器的时候,如果使用remove,add等方法的时候都会修改modCount,
  83.          *在迭代的时候需要保持单线程的唯一操作,如果期间进行了插入或者删除,modCount就会被修改,迭代器就会检测到被并发修改,从而出现运行时异常。
  84.          *举个简单的例子,现在某个线程正在遍历一个List,另一个线程对List中的某个值做了删除,那原来的线程用原来的迭代器当然无法正常遍历了
  85.          */
  86.         int expectedModCount = modCount;
  87.         public boolean hasNext() {
  88.             return cursor != size(); //当索引值和元素个数相同时表示没有下一个元素了,索引是从0到size-1
  89.         }
  90.         public E next() {
  91.             checkForComodification(); //检查modCount是否改变
  92.             try {
  93.                 int i = cursor; //next()方法主要做了两件事:
  94.                 E next = get(i);
  95.                 lastRet = i;
  96.                 cursor = i + 1; //1.将索引指向了下一个位置
  97.                 return next; //2. 返回当前索引的值
  98.             } catch (IndexOutOfBoundsException e) {
  99.                 checkForComodification();
  100.                 throw new NoSuchElementException();
  101.             }
  102.         }
  103.         public void remove() {
  104.             if (lastRet < 0) //lastRet<0表示已经不存在了
  105.                 throw new IllegalStateException();
  106.             checkForComodification();
  107.             try {
  108.                 AbstractList.this.remove(lastRet);
  109.                 if (lastRet < cursor)
  110.                     cursor–; //原位置的索引值减小了1,但是实际位置没变
  111.                 lastRet = -1; //置为-1表示已删除
  112.                 expectedModCount = modCount;
  113.             } catch (IndexOutOfBoundsException e) {
  114.                 throw new ConcurrentModificationException();
  115.             }
  116.         }
  117.         final void checkForComodification() {
  118.             if (modCount != expectedModCount)
  119.                 throw new ConcurrentModificationException();
  120.         }
  121.     }
  122.     private class ListItr extends Itr implements ListIterator<E> {
  123.         ListItr(int index) {
  124.             cursor = index;
  125.         }
  126.         public boolean hasPrevious() {
  127.             return cursor != 0;
  128.         }
  129.         public E previous() {
  130.             checkForComodification();
  131.             try {
  132.                 int i = cursor – 1; //previous()方法中也做了两件事:
  133.                 E previous = get(i); //1. 将索引向前移动一位
  134.                 lastRet = cursor = i; //2. 返回索引处的值
  135.                 return previous;
  136.             } catch (IndexOutOfBoundsException e) {
  137.                 checkForComodification();
  138.                 throw new NoSuchElementException();
  139.             }
  140.         }
  141.         public int nextIndex() { //iterator中的index本来就是下一个位置,在next()方法中可以看出
  142.             return cursor;
  143.         }
  144.         public int previousIndex() {
  145.             return cursor-1;
  146.         }
  147.         public void set(E e) { //修改当前位置的元素
  148.             if (lastRet < 0)
  149.                 throw new IllegalStateException();
  150.             checkForComodification();
  151.             try {
  152.                 AbstractList.this.set(lastRet, e);
  153.                 expectedModCount = modCount;
  154.             } catch (IndexOutOfBoundsException ex) {
  155.                 throw new ConcurrentModificationException();
  156.             }
  157.         }
  158.         public void add(E e) { //在当前位置添加元素
  159.             checkForComodification();
  160.             try {
  161.                 int i = cursor;
  162.                 AbstractList.this.add(i, e);
  163.                 lastRet = -1;
  164.                 cursor = i + 1;
  165.                 expectedModCount = modCount;
  166.             } catch (IndexOutOfBoundsException ex) {
  167.                 throw new ConcurrentModificationException();
  168.             }
  169.         }
  170.     }
  171. /**********************************************************************************/
  172.     //获得子List,详细源码往下看SubList类
  173.     public List<E> subList(int fromIndex, int toIndex) {
  174.         return (this instanceof RandomAccess ?
  175.                 new RandomAccessSubList<>(this, fromIndex, toIndex) :
  176.                 new SubList<>(this, fromIndex, toIndex));
  177.     }
  178. /*************************** Comparison and hashing *******************************/
  179.     public boolean equals(Object o) {
  180.         if (o == this)
  181.             return true;
  182.         if (!(o instanceof List))
  183.             return false;
  184.         ListIterator<E> e1 = listIterator();
  185.         ListIterator e2 = ((List) o).listIterator();
  186.         while (e1.hasNext() && e2.hasNext()) {
  187.             E o1 = e1.next();
  188.             Object o2 = e2.next();
  189.             if (!(o1==null ? o2==null : o1.equals(o2)))
  190.                 return false;
  191.         }
  192.         return !(e1.hasNext() || e2.hasNext());
  193.     }
  194.     public int hashCode() { //hashcode
  195.         int hashCode = 1;
  196.         for (E e : this)
  197.             hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
  198.         return hashCode;
  199.     }
  200. /**********************************************************************************/
  201.     protected transient int modCount = 0;
  202.     private void rangeCheckForAdd(int index) {
  203.         if (index < 0 || index > size())
  204.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  205.     }
  206.     private String outOfBoundsMsg(int index) {
  207.         return “Index: ”+index+“, Size: ”+size();
  208.     }
  209. }
  210. class SubList<E> extends AbstractList<E> {
  211.     private final AbstractList<E> l;
  212.     private final int offset;
  213.     private int size;
  214.     /* 从SubList源码可以看出,当需要获得一个子List时,底层并不是真正的返回一个子List,还是原来的List,只不过
  215.     * 在操作的时候,索引全部限定在用户所需要的子List部分而已
  216.     */
  217.     SubList(AbstractList<E> list, int fromIndex, int toIndex) {
  218.         if (fromIndex < 0)
  219.             throw new IndexOutOfBoundsException(“fromIndex = ” + fromIndex);
  220.         if (toIndex > list.size())
  221.             throw new IndexOutOfBoundsException(“toIndex = ” + toIndex);
  222.         if (fromIndex > toIndex)
  223.             throw new IllegalArgumentException(“fromIndex(“ + fromIndex +
  224.                                                ”) > toIndex(“ + toIndex + “)”);
  225.         l = list; //原封不动的将原来的list赋给l
  226.         offset = fromIndex; //偏移量,用在操作新的子List中
  227.         size = toIndex – fromIndex; //子List的大小,所以子List中不包括toIndex处的值,即子List中包括左边不包括右边
  228.         this.modCount = l.modCount;
  229.     }
  230.     //注意下面所有的操作都在索引上加上偏移量offset,相当于在原来List的副本上操作子List
  231.     public E set(int index, E element) {
  232.         rangeCheck(index);
  233.         checkForComodification();
  234.         return l.set(index+offset, element);
  235.     }
  236.     public E get(int index) {
  237.         rangeCheck(index);
  238.         checkForComodification();
  239.         return l.get(index+offset);
  240.     }
  241.     public int size() {
  242.         checkForComodification();
  243.         return size;
  244.     }
  245.     public void add(int index, E element) {
  246.         rangeCheckForAdd(index);
  247.         checkForComodification();
  248.         l.add(index+offset, element);
  249.         this.modCount = l.modCount;
  250.         size++;
  251.     }
  252.     public E remove(int index) {
  253.         rangeCheck(index);
  254.         checkForComodification();
  255.         E result = l.remove(index+offset);
  256.         this.modCount = l.modCount;
  257.         size–;
  258.         return result;
  259.     }
  260.     protected void removeRange(int fromIndex, int toIndex) {
  261.         checkForComodification();
  262.         l.removeRange(fromIndex+offset, toIndex+offset);
  263.         this.modCount = l.modCount;
  264.         size -= (toIndex-fromIndex);
  265.     }
  266.     public boolean addAll(Collection<? extends E> c) {
  267.         return addAll(size, c);
  268.     }
  269.     public boolean addAll(int index, Collection<? extends E> c) {
  270.         rangeCheckForAdd(index);
  271.         int cSize = c.size();
  272.         if (cSize==0)
  273.             return false;
  274.         checkForComodification();
  275.         l.addAll(offset+index, c);
  276.         this.modCount = l.modCount;
  277.         size += cSize;
  278.         return true;
  279.     }
  280.     public Iterator<E> iterator() {
  281.         return listIterator();
  282.     }
  283.     public ListIterator<E> listIterator(final int index) {
  284.         checkForComodification();
  285.         rangeCheckForAdd(index);
  286.         return new ListIterator<E>() {
  287.             private final ListIterator<E> i = l.listIterator(index+offset); //相当子List的索引0
  288.             public boolean hasNext() {
  289.                 return nextIndex() < size;
  290.             }
  291.             public E next() {
  292.                 if (hasNext())
  293.                     return i.next();
  294.                 else
  295.                     throw new NoSuchElementException();
  296.             }
  297.             public boolean hasPrevious() {
  298.                 return previousIndex() >= 0;
  299.             }
  300.             public E previous() {
  301.                 if (hasPrevious())
  302.                     return i.previous();
  303.                 else
  304.                     throw new NoSuchElementException();
  305.             }
  306.             public int nextIndex() {
  307.                 return i.nextIndex() – offset;
  308.             }
  309.             public int previousIndex() {
  310.                 return i.previousIndex() – offset;
  311.             }
  312.             public void remove() {
  313.                 i.remove();
  314.                 SubList.this.modCount = l.modCount;
  315.                 size–;
  316.             }
  317.             public void set(E e) {
  318.                 i.set(e);
  319.             }
  320.             public void add(E e) {
  321.                 i.add(e);
  322.                 SubList.this.modCount = l.modCount;
  323.                 size++;
  324.             }
  325.         };
  326.     }
  327.     public List<E> subList(int fromIndex, int toIndex) {
  328.         return new SubList<>(this, fromIndex, toIndex);
  329.     }
  330.     private void rangeCheck(int index) {
  331.         if (index < 0 || index >= size)
  332.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  333.     }
  334.     private void rangeCheckForAdd(int index) {
  335.         if (index < 0 || index > size)
  336.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  337.     }
  338.     private String outOfBoundsMsg(int index) {
  339.         return “Index: ”+index+“, Size: ”+size;
  340.     }
  341.     private void checkForComodification() {
  342.         if (this.modCount != l.modCount)
  343.             throw new ConcurrentModificationException();
  344.     }
  345. }
  346. class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
  347.     RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
  348.         super(list, fromIndex, toIndex);
  349.     }
  350.     public List<E> subList(int fromIndex, int toIndex) {
  351.         return new RandomAccessSubList<>(this, fromIndex, toIndex);
  352.     }
  353. }
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();
    }

/***************************** Search Operations**********************************/
    public int indexOf(Object o) { //搜索对象o的索引
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null) //执行it.next(),会先返回it指向位置的值,然后it会移到下一个位置
                    return it.previousIndex(); //所以要返回it.previousIndex(); 关于it几个方法的源码在下面
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -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;
    }
/**********************************************************************************/

/****************************** Bulk Operations ***********************************/
    public void clear() {
        removeRange(0, size());
    }

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

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

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

    public ListIterator<E> listIterator() {
        return listIterator(0); //返回的iterator索引从0开始
    }

    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index); //首先检查index范围是否正确

        return new ListItr(index); //ListItr继承与Itr且实现了ListIterator接口,Itr实现了Iterator接口,往下看
    }

    private class Itr implements Iterator<E> {        
        int cursor = 0; //元素的索引,当调用next()方法时,返回当前索引的值
        int lastRet = -1; //lastRet也是元素的索引,但如果删掉此元素,该值置为-1
         /*
         *迭代器都有个modCount值,在使用迭代器的时候,如果使用remove,add等方法的时候都会修改modCount,
         *在迭代的时候需要保持单线程的唯一操作,如果期间进行了插入或者删除,modCount就会被修改,迭代器就会检测到被并发修改,从而出现运行时异常。
         *举个简单的例子,现在某个线程正在遍历一个List,另一个线程对List中的某个值做了删除,那原来的线程用原来的迭代器当然无法正常遍历了
         */
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size(); //当索引值和元素个数相同时表示没有下一个元素了,索引是从0到size-1
        }

        public E next() {
            checkForComodification(); //检查modCount是否改变
            try {
                int i = cursor; //next()方法主要做了两件事:
                E next = get(i); 
                lastRet = i;
                cursor = i + 1; //1.将索引指向了下一个位置
                return next; //2. 返回当前索引的值
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0) //lastRet<0表示已经不存在了
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--; //原位置的索引值减小了1,但是实际位置没变
                lastRet = -1; //置为-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; //previous()方法中也做了两件事:
                E previous = get(i); //1. 将索引向前移动一位
                lastRet = cursor = i; //2. 返回索引处的值
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public int nextIndex() { //iterator中的index本来就是下一个位置,在next()方法中可以看出
            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();
            }
        }
    }
/**********************************************************************************/

    //获得子List,详细源码往下看SubList类
    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }

/*************************** Comparison and hashing *******************************/
    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() { //hashcode
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }
/**********************************************************************************/ 
    protected transient int modCount = 0;

    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size())
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size();
    }
}

class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;
    private final int offset;
    private int size;
    /* 从SubList源码可以看出,当需要获得一个子List时,底层并不是真正的返回一个子List,还是原来的List,只不过
    * 在操作的时候,索引全部限定在用户所需要的子List部分而已
    */
    SubList(AbstractList<E> list, int fromIndex, int toIndex) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
        l = list; //原封不动的将原来的list赋给l
        offset = fromIndex; //偏移量,用在操作新的子List中
        size = toIndex - fromIndex; //子List的大小,所以子List中不包括toIndex处的值,即子List中包括左边不包括右边
        this.modCount = l.modCount;
    }
    //注意下面所有的操作都在索引上加上偏移量offset,相当于在原来List的副本上操作子List
    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return l.set(index+offset, element);
    }

    public E get(int index) {
        rangeCheck(index);
        checkForComodification();
        return l.get(index+offset);
    }

    public int size() {
        checkForComodification();
        return size;
    }

    public void add(int index, E element) {
        rangeCheckForAdd(index);
        checkForComodification();
        l.add(index+offset, element);
        this.modCount = l.modCount;
        size++;
    }

    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        size--;
        return result;
    }

    protected void removeRange(int fromIndex, int toIndex) {
        checkForComodification();
        l.removeRange(fromIndex+offset, toIndex+offset);
        this.modCount = l.modCount;
        size -= (toIndex-fromIndex);
    }

    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        int cSize = c.size();
        if (cSize==0)
            return false;

        checkForComodification();
        l.addAll(offset+index, c);
        this.modCount = l.modCount;
        size += cSize;
        return true;
    }

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

    public ListIterator<E> listIterator(final int index) {
        checkForComodification();
        rangeCheckForAdd(index);

        return new ListIterator<E>() {
            private final ListIterator<E> i = l.listIterator(index+offset); //相当子List的索引0

            public boolean hasNext() {
                return nextIndex() < size;
            }

            public E next() {
                if (hasNext())
                    return i.next();
                else
                    throw new NoSuchElementException();
            }

            public boolean hasPrevious() {
                return previousIndex() >= 0;
            }

            public E previous() {
                if (hasPrevious())
                    return i.previous();
                else
                    throw new NoSuchElementException();
            }

            public int nextIndex() {
                return i.nextIndex() - offset;
            }

            public int previousIndex() {
                return i.previousIndex() - offset;
            }

            public void remove() {
                i.remove();
                SubList.this.modCount = l.modCount;
                size--;
            }

            public void set(E e) {
                i.set(e);
            }

            public void add(E e) {
                i.add(e);
                SubList.this.modCount = l.modCount;
                size++;
            }
        };
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return new SubList<>(this, fromIndex, toIndex);
    }

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

    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    private void checkForComodification() {
        if (this.modCount != l.modCount)
            throw new ConcurrentModificationException();
    }
}

class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        super(list, fromIndex, toIndex);
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return new RandomAccessSubList<>(this, fromIndex, toIndex);
    }
}

6. AbstractSet

AbstractSet的定义如下:

  1. public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {}
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {}

AbstractSet是一个继承与AbstractCollection,并且实现了Set接口的抽象类。由于Set接口和Collection接口中的API完全一样,所以Set也就没有自己单独的API。和AbstractCollection一样,它实现了List中除iterator()和size()外的方法。所以源码和AbstractCollection的一样。
AbstractSet的主要作用:它实现了Set接口总的大部分函数,从而方便其他类实现Set接口。

7. Iterator

Iterator的定义如下:

  1. public interface Iterator<E> {}
public interface Iterator<E> {}

Iterator是一个接口,它是集合的迭代器。集合可以通过Iterator去遍历其中的元素。Iterator提供的API接口包括:是否存在下一个元素,获取下一个元素和删除当前元素。

注意:Iterator遍历Collection时,是fail-fast机制的。即,当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了,那么线程A访问集合时,就会抛出CurrentModificationException异常,产生fail-fast事件。下面是Iterator的几个API。

  1. // Iterator的API
  2. abstract boolean hasNext()
  3. abstract E next()
  4. abstract void remove()
// Iterator的API
abstract boolean hasNext()
abstract E next()
abstract void remove()

8. ListIterator

ListIterator的定义如下:

  1. public interface ListIterator<E> extends Iterator<E> {}
public interface ListIterator<E> extends Iterator<E> {}

ListIterator是一个继承Iterator的接口,它是队列迭代器。专门用于遍历List,能提供向前和向后遍历。相比于Iterator,它新增了添加、是否存在上一个元素、获取上一个元素等API接口:

  1. // 继承于Iterator的接口
  2. abstract boolean hasNext()
  3. abstract E next()
  4. abstract void remove()
  5. // 新增API接口
  6. abstract void add(E object)
  7. abstract boolean hasPrevious()
  8. abstract int nextIndex()
  9. abstract E previous()
  10. abstract int previousIndex()
  11. abstract void set(E object)
// 继承于Iterator的接口
abstract boolean hasNext()
abstract E next()
abstract void remove()
// 新增API接口
abstract void add(E object)
abstract boolean hasPrevious()
abstract int nextIndex()
abstract E previous()
abstract int previousIndex()
abstract void set(E object)

Collection的架构就讨论到这吧,如果有问题欢迎留言指正~

_____________________________________________________________________________________________________________________________________________________

—–乐于分享,共同进步!

—–更多文章请看:http://blog.csdn.net/eson_15

    原文作者:java集合源码分析
    原文地址: https://blog.csdn.net/PORSCHE_GT3RS/article/details/78291005
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞