java集合框架02——Collection架构与源码分析

简介:

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


        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的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public interface Collection<E> extends Iterable<E> {}  
        从它的定义中可以看出,Collection是一个接口。它是一个高度抽象出来的集合,包含了集合的基本操作:添加、删除、清空、遍历、是否为空、获取大小等。

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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()  

2. List

        List的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public interface List<E> extends Collection<E> {}  
        从List定义中可以看出,它继承与Collection接口,即List是集合的一种。List是有序的队列,List中的每一个元素都有一个索引,第一个元素的索引值为0,往后的元素的索引值依次+1.,List中允许有重复的元素。

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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  

3. Set

        Set的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public interface Set<E> extends Collection<E> {}  
        Set也继承与Collection接口,且里面不能有重复元素。关于API,Set与Collection的API完全一样,不在赘述。

4. AbstractCollection

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public abstract class AbstractCollection<E> implements Collection<E> {}  

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

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

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

5. AbstractList

        AbstractList的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 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抽象类的源码如下:

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

6. AbstractSet

        AbstractSet的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 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的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public interface Iterator<E> {}  
        Iterator是一个接口,它是集合的迭代器。集合可以通过Iterator去遍历其中的元素。Iterator提供的API接口包括:是否存在下一个元素,获取下一个元素和删除当前元素。

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // Iterator的API  
  2. abstract boolean hasNext()  
  3. abstract E next()  
  4. abstract void remove()  

8. ListIterator

        ListIterator的定义如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public interface ListIterator<E> extends Iterator<E> {}  

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

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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)  

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


转载:http://blog.csdn.net/eson_15/article/details/51139978

目录
相关文章
|
23天前
|
Java
【Java】如果一个集合中类型是String如何使用拉姆达表达式 进行Bigdecimal类型计算?
【Java】如果一个集合中类型是String如何使用拉姆达表达式 进行Bigdecimal类型计算?
24 0
|
25天前
|
消息中间件 架构师 NoSQL
咕炮课堂Java架构师课程
针对1-5年经验开发者,【Java架构师培训】聚焦互联网热门技术,如Redis、MongoDB、Dubbo、Zookeeper、Kafka,讲授高并发、高可用分布式解决方案。由资深讲师指导,提升技术水平。
26 2
咕炮课堂Java架构师课程
|
28天前
|
算法 Java 数据处理
Java集合框架的优缺点
Java集合框架的优缺点
|
1月前
|
网络协议 算法 Java
|
1天前
|
负载均衡 Java 开发者
细解微服务架构实践:如何使用Spring Cloud进行Java微服务治理
【4月更文挑战第17天】Spring Cloud是Java微服务治理的首选框架,整合了Eureka(服务发现)、Ribbon(客户端负载均衡)、Hystrix(熔断器)、Zuul(API网关)和Config Server(配置中心)。通过Eureka实现服务注册与发现,Ribbon提供负载均衡,Hystrix实现熔断保护,Zuul作为API网关,Config Server集中管理配置。理解并运用Spring Cloud进行微服务治理是现代Java开发者的关键技能。
|
6天前
|
存储 Java 编译器
Java集合丛林:深入了解集合框架的秘密
Java集合丛林:深入了解集合框架的秘密
11 0
Java集合丛林:深入了解集合框架的秘密
|
9天前
|
Java BI
Java 获取周,月,年日期集合(统计图)
Java 获取周,月,年日期集合(统计图)
Java 获取周,月,年日期集合(统计图)
|
14天前
|
消息中间件 安全 Java
解密 Java 后台架构设计之道
【4月更文挑战第5天】本文探讨了Java后台架构设计的最佳实践,包括分层架构、微服务、异步处理与消息队列、RESTful API设计、数据库优化、安全控制、容错高可用、配置管理、CI/CD和监控日志。强调了使用微服务、Spring Boot/Spring Cloud、异步消息队列、RESTful API、安全框架Spring Security等技术的重要性,以及监控和自动化部署在确保系统稳定性和效率上的关键角色。通过这些实践,开发者能构建高效、稳定且可扩展的后台系统。
|
20天前
|
存储 安全 Java
【Java技术专题】「Guava开发指南」手把手教你如何进行使用Guava工具箱进行开发系统实战指南(不可变集合篇)
【Java技术专题】「Guava开发指南」手把手教你如何进行使用Guava工具箱进行开发系统实战指南(不可变集合篇)
30 1
|
28天前
|
缓存 NoSQL Java
java中复杂业务情况下的集合操作(增减集合同步数据)
java中复杂业务情况下的集合操作(增减集合同步数据)
26 0