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對象。

 Collection的定義如下:

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()

. List

        List的定義如下 

 

從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

3. Set

 

Set的定義如下:

 

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

        Set也繼承與Collection接口,且裏面不能有重複元素。關於API,Set與Collection的API完全一樣,不在贅述。

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

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

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接口。

 AbstractSet是一個繼承與AbstractCollection,並且實現了Set接口的抽象類。由於Set接口和Collection接口中的API完全一樣,所以Set也就沒有自己單獨的API。和AbstractCollection一樣,它實現了List中除iterator()和size()外的方法。所以源碼和AbstractCollection的一樣。
        AbstractSet的主要作用:它實現了Set接口總的大部分函數,從而方便其他類實現Set接口。

 Iterator的定義如下:

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()

8. ListIterator

        ListIterator的定義如下:

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)

Collection的架構就討論到這吧,如果有問題歡迎留言指正~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章