一點一點看JDK源碼(三)java.util.ArrayList 前偏

一點一點看JDK源碼(三)java.util.ArrayListhtml

 

liuyuhang原創,未經容許禁止轉載java

本文舉例使用的是JDK8的API算法

 

目錄:一點一點看JDK源碼(〇)

1.綜述數組

  ArrayList是一個容量不固定的容器,爲單列,有序集合,容量可擴容,擴容係數爲1.5緩存

  有最大值,通常達不到。安全

  ArrayList是線程不安全的,其擴容發生於集合修改的時候,如add,addAll等app

  ArrayList底層使用的是Object數組,初始化內容爲10個容量的元素less

  使用ArrayList的時候,幾種狀況下實例化將更加提升效率dom

    ①僅僅使用基礎增長功能做爲容器臨時使用ide

      List list = new ArrayList()

      這樣可使用較少的實例化方法

    ②使用ArrayList中的全部實例化方法時使用

      ArrayList list = new ArrayList()

      這樣可使用ArrayList全部的方法

    ③若是你能肯定這個集合的容量,最好指定其容量,

      擴容也是一種算法,並且可能擴容屢次,效率不高,如:

      ArrayList list = new ArrayList(22)

    ④若是該ArrayList的長度巨大,而且不肯定,只用於容器臨時使用

      建議使用LinkedList進行接收參數,而後再轉化爲ArrayList,如:

      LinkedList list = new LinkedList();

      //some operations

      ArrayList listArr = new ArrayList(list);

  

2.關注點

  • Collection
  • List
  • LinkedList
  • Vector

  關注點

    Collection爲父接口的父接口

    List爲父接口

    LinkedList爲List的鏈表實現,ArrayList爲List的數組實現

    Vector幾乎不去用,他是List的另外一種數組實現,可是線程安全

 

  雖然類註釋上的@see只有這些,可是我的認爲,

  應該重點關注一下AbstractList抽象類,RandomAccess,Cloneable這兩個接口,序列化接口關注度真心不高

  對於接口的實現關係,哪些是List通用的,哪些內容已經在AbstractList抽象類中已經定義了,應該過一下的

 

3.源碼解析

  放源碼以下,註解有些刪掉,對於類,內部類,方法,構造等進行了簡要的說明註釋

 

  內容比較多,建議慢慢看完,若是jdk1.8新增的看不懂,能夠暫時擱置,略過

  我也不保證對於jdk1.8的部分註釋是正確的。

 

   1 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
   2     /**
   3      * 序列化版本號
   4      */
   5     private static final long serialVersionUID = 8683452581122892189L;
   6     /**
   7      * 默認容量。
   8      */
   9     private static final int DEFAULT_CAPACITY = 10;
  10 
  11     /**
  12      * 以object數組做爲類內共享實例容器。
  13      */
  14     private static final Object[] EMPTY_ELEMENTDATA = {};
  15 
  16     /**
  17      * 以object數組做爲類內共享實例容器,使用默認容量實例化時使用。
  18      */
  19     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  20 
  21     /**
  22      * 以object數組做爲容器緩自排序衝數組,注意沒有private關鍵字,用於排序,當地一個元素添加的時候將轉爲默認容量
  23      */
  24     transient Object[] elementData; // non-private to simplify nested class access
  25 
  26     /**
  27      * 緩存的size大小,
  28      */
  29     private int size;
  30 
  31     /**
  32      * 帶參構造,手動設置容器初始大小,若實例化時能肯定大小,最好別使用默認擴展容量,將提升運行效率
  33      */
  34     public ArrayList(int initialCapacity) {
  35         if (initialCapacity > 0) {
  36             this.elementData = new Object[initialCapacity]; //使用自排序緩衝數組
  37         } else if (initialCapacity == 0) {
  38             this.elementData = EMPTY_ELEMENTDATA; //使用默認數組
  39         } else {
  40             throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); //容量擴充參數異常
  41         }
  42     }
  43 
  44     /**
  45      * 無參構造,使用默認容器初始化大小
  46      */
  47     public ArrayList() {
  48         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  49     }
  50 
  51     /**
  52      * 帶參構造器,將參數集合用數組工具類轉成數組,並存入緩衝數組,對緩衝數組進行校驗.
  53 * 若轉換後的數組並不是object數組(內嵌套沒法直接引用狀況下),則使用數組工具類將該數組使用深度拷貝
  54      */
  55     public ArrayList(Collection<? extends E> c) {
  56         elementData = c.toArray();
  57         if ((size = elementData.length) != 0) {
  58             // c.toArray might (incorrectly) not return Object[] (see 6260652)
  59             if (elementData.getClass() != Object[].class)
  60                 elementData = Arrays.copyOf(elementData, size, Object[].class);
  61         } else {
  62             // replace with empty array.
  63             this.elementData = EMPTY_ELEMENTDATA;
  64         }
  65     }
  66 
  67     /**
  68      * 去除多餘的數組申請空間,在內存緊張時會用到
  69      */
  70     public void trimToSize() {
  71         modCount++;//修改次數
  72         if (size < elementData.length) {
  73             elementData = (size == 0)
  74               ? EMPTY_ELEMENTDATA
  75               : Arrays.copyOf(elementData, size);
  76         }
  77     }
  78 
  79     /**
  80      * 對底層緩衝數組進行擴容的優化方法,若是已知該ArrayList容量,則可執行一次性擴容,
  81      * 不然將在數組add的過程當中進行動態擴容,效率較低
  82      */
  83     public void ensureCapacity(int minCapacity) {
  84         int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0: DEFAULT_CAPACITY;
  85         if (minCapacity > minExpand) {
  86             ensureExplicitCapacity(minCapacity);
  87         }
  88     }
  89     /**
  90      * 從新計算ArrayList的size,在使用構造和擴容時調用
  91      */
  92     private static int calculateCapacity(Object[] elementData, int minCapacity) {
  93         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  94             return Math.max(DEFAULT_CAPACITY, minCapacity);
  95         }
  96         return minCapacity;
  97     }
  98 
  99     /**
 100      * 被add調用,內部調用calculatecapacity,用於擴容
 101      */
 102     private void ensureCapacityInternal(int minCapacity) {
 103         ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
 104     }
 105 
 106     /**
 107      * 被ensureCapacity調用,內部調用calculatecapacity,用於擴容或優化
 108      */
 109     private void ensureExplicitCapacity(int minCapacity) {
 110         modCount++;
 111         // overflow-conscious code
 112         if (minCapacity - elementData.length > 0)
 113             grow(minCapacity);
 114     }
 115 
 116     /**
 117      * 目標分配數組的容器大小,最大值要小於Integer.MAX_VALUE-8
 118      */
 119     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 120 
 121     /**
 122      * 擴容
 123      */
 124     private void grow(int minCapacity) {
 125         int oldCapacity = elementData.length; //原容量
 126         int newCapacity = oldCapacity + (oldCapacity >> 1); //新容量,擴容1.5倍,自查>>位運算
 127         if (newCapacity - minCapacity < 0) //容量不足,則擴容
 128             newCapacity = minCapacity;
 129         if (newCapacity - MAX_ARRAY_SIZE > 0) //擴容超支,使用最大容
 130             newCapacity = hugeCapacity(minCapacity);
 131         // minCapacity is usually close to size, so this is a win:
 132         elementData = Arrays.copyOf(elementData, newCapacity);
 133     }
 134 /**
 135      * 被grow方法調用,擴容爲最大
 136      */
 137     private static int hugeCapacity(int minCapacity) {
 138         if (minCapacity < 0) //參數錯誤,拋出異常
 139             throw new OutOfMemoryError();
 140         return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; //返回最大容量
 141     }
 142 
 143     /**
 144      * 獲取當前size
 145      */
 146     public int size() {
 147         return size;
 148     }
 149 
 150     /**
 151      * 判斷當前是size是否爲0,容器是否爲空
 152      */
 153     public boolean isEmpty() {
 154         return size == 0;
 155     }
 156 
 157     /**
 158      * 判斷是否包含元素o,返回該元素的index是否大於等於0的判斷,是爲包含,否爲不包含
 159      */
 160     public boolean contains(Object o) {
 161         return indexOf(o) >= 0;
 162     }
 163 
 164     /**
 165      * 獲取查詢元素的index,若備查元素爲null,則尋找空元素,返回index
 166      * 若備查元素不爲null,則使用equal判斷該元素是否存在,並返回index
 167      * 不存在則返回-1
 168      * 被contains調用
 169      */
 170     public int indexOf(Object o) {
 171         if (o == null) {
 172             for (int i = 0; i < size; i++)
 173                 if (elementData[i]==null)
 174                     return i;
 175         } else {
 176             for (int i = 0; i < size; i++)
 177                 if (o.equals(elementData[i]))
 178                     return i;
 179         }
 180         return -1;
 181     }
 182 
 183     /**
 184      * 倒敘查詢第一個出現的被查元素
 185      */
 186     public int lastIndexOf(Object o) {
 187         if (o == null) {
 188             for (int i = size-1; i >= 0; i--)
 189                 if (elementData[i]==null)
 190                     return i;
 191         } else {
 192             for (int i = size-1; i >= 0; i--)
 193                 if (o.equals(elementData[i]))
 194                     return i;
 195         }
 196         return -1;
 197     }
 198 
 199     /**
 200      * clone本實例數組,返回類型爲Object,使用根類意爲可轉換爲其餘格式容器
 201      */
 202     public Object clone() {
 203         try {
 204             ArrayList<?> v = (ArrayList<?>) super.clone();
 205             v.elementData = Arrays.copyOf(elementData, size);
 206             v.modCount = 0;
 207             return v;
 208         } catch (CloneNotSupportedException e) {
 209             throw new InternalError(e);
 210         }
 211     }
 212 
 213     /**
 214      * 將本實例轉換爲object數組,調用數組工具類拷貝
 215      */
 216     public Object[] toArray() {
 217         return Arrays.copyOf(elementData, size);
 218     }
 219 
 220     /**
 221      * 將本實例轉換爲指定類型數組,調用數組工具類拷貝,並得到泛型的Class
 222      */
 223     @SuppressWarnings("unchecked")
 224     public <T> T[] toArray(T[] a) {
 225         if (a.length < size)
 226             // Make a new array of a's runtime type, but my contents:
 227             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 228         System.arraycopy(elementData, 0, a, 0, size);
 229         if (a.length > size)
 230             a[size] = null;
 231         return a;
 232     }
 233 
 234     /**
 235      * 獲取指定index的元素,被get方法調用,get方法內進行check,util包內的類可調用
 236      */
 237     @SuppressWarnings("unchecked")
 238     E elementData(int index) {
 239         return (E) elementData[index];
 240     }
 241 
 242     /**
 243      * 獲取指定元素的方法,使用rangeCheck進行index的check
 244      */
 245     public E get(int index) {
 246         rangeCheck(index);
 247         return elementData(index);
 248     }
 249 
 250     /**
 251      * 將指定index的值設置爲指定值,使用rangeCheck進行index的check
 252      */
 253     public E set(int index, E element) {
 254         rangeCheck(index);
 255         E oldValue = elementData(index);
 256         elementData[index] = element;
 257         return oldValue;
 258     }
 259 
 260     /**
 261      * 容量+1的,在容器尾部添加元素
 262      */
 263     public boolean add(E e) {
 264         ensureCapacityInternal(size + 1);  // Increments modCount!!
 265         elementData[size++] = e; // 這個在數組尾部追加元素的寫法很好用,前提是擴容
 266         return true; // 有返回值的,應當接收
 267     }
 268 
 269     /**
 270      * 在指定index添加指定元素,首先使用rangeCheckForAdd進行check,爲保證數組操做的正確性,使用arraycopy來移動數組元素
 271      */
 272     public void add(int index, E element) {
 273         rangeCheckForAdd(index);
 274         ensureCapacityInternal(size + 1);  // Increments modCount!!
 275         System.arraycopy(elementData, index, elementData, index + 1, size - index);
 276         elementData[index] = element;
 277         size++;
 278     }
 279 
 280     /**
 281      * remove指定index的元素,並重構本實例
 282      */
 283     public E remove(int index) {
 284         rangeCheck(index);
 285         modCount++;
 286         E oldValue = elementData(index);
 287         int numMoved = size - index - 1;
 288         if (numMoved > 0)
 289             System.arraycopy(elementData, index+1, elementData, index, numMoved);
 290         elementData[--size] = null; // clear to let GC do its work
 291         return oldValue;
 292     }
 293 
 294     /**
 295      * remove指定元素,返回是否找到該元素並移除成功的boolean標記
 296      */
 297     public boolean remove(Object o) {
 298         if (o == null) {
 299             for (int index = 0; index < size; index++)
 300                 if (elementData[index] == null) {
 301                     fastRemove(index);
 302                     return true;
 303                 }
 304         } else {
 305             for (int index = 0; index < size; index++)
 306                 if (o.equals(elementData[index])) {
 307                     fastRemove(index);
 308                     return true;
 309                 }
 310         }
 311         return false;
 312     }
 313 
 314     /*
 315      * 內部使用,快速移除指定index的元素
 316      */
 317     private void fastRemove(int index) {
 318         modCount++;
 319         int numMoved = size - index - 1;
 320         if (numMoved > 0)
 321             System.arraycopy(elementData, index+1, elementData, index,
 322                              numMoved);
 323         elementData[--size] = null; // clear to let GC do its work
 324     }
 325 
 326     /**
 327      * 清除本實例內部的全部元素,加速gc回收
 328      */
 329     public void clear() {
 330         modCount++;
 331         // clear to let GC do its work
 332         for (int i = 0; i < size; i++)
 333             elementData[i] = null;
 334         size = 0;
 335     }
 336 
 337     /**
 338      * 添加指定集合到本實例中Object數組末尾
 339      */
 340     public boolean addAll(Collection<? extends E> c) {
 341         Object[] a = c.toArray();
 342         int numNew = a.length;
 343         ensureCapacityInternal(size + numNew);  // Increments modCount
 344         System.arraycopy(a, 0, elementData, size, numNew);
 345         size += numNew;
 346         return numNew != 0;
 347     }
 348 
 349     /**
 350      * 從指定元素開始添加指定集合到本實例
 351      */
 352     public boolean addAll(int index, Collection<? extends E> c) {
 353         rangeCheckForAdd(index);
 354         Object[] a = c.toArray();
 355         int numNew = a.length;
 356         ensureCapacityInternal(size + numNew);  // Increments modCount
 357         int numMoved = size - index;
 358         if (numMoved > 0)
 359             System.arraycopy(elementData, index, elementData, index + numNew,
 360                              numMoved);
 361         System.arraycopy(a, 0, elementData, index, numNew);
 362         size += numNew;
 363         return numNew != 0;
 364     }
 365 
 366     /**
 367      * 本類和子類可以使用,移除指定範圍的index的全部元素
 368      */
 369     protected void removeRange(int fromIndex, int toIndex) {
 370         modCount++;
 371         int numMoved = size - toIndex;
 372         System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
 373         int newSize = size - (toIndex-fromIndex);
 374         for (int i = newSize; i < size; i++) {
 375             elementData[i] = null;
 376         }
 377         size = newSize;
 378     }
 379 
 380     /**
 381      * 內部的index超限檢測方法,當index超過size的時候,拋出index超限異常,在本類中被屢次調用
 382      */
 383     private void rangeCheck(int index) {
 384         if (index >= size)
 385             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 386     }
 387 
 388     /**
 389      * 同上,可是在add和addAll中專用
 390      */
 391     private void rangeCheckForAdd(int index) {
 392         if (index > size || index < 0)
 393             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 394     }
 395 
 396     /**
 397      * index超限拋異常時使用,用來提示size和index的值
 398      */
 399     private String outOfBoundsMsg(int index) {
 400         return "Index: "+index+", Size: "+size;
 401     }
 402 
 403     /**
 404      * 從本類實例中移除指定集合中全部元素的方法,返回值應接收
 405      */
 406     public boolean removeAll(Collection<?> c) {
 407         Objects.requireNonNull(c);
 408         return batchRemove(c, false);
 409     }
 410 
 411     /**
 412      * 從本類實例中保留指定集合中全部元素的方法,與removeAll相反
 413      */
 414     public boolean retainAll(Collection<?> c) {
 415         Objects.requireNonNull(c);
 416         return batchRemove(c, true);
 417     }
 418 
 419     /**
 420      * 內部調用,若是參數集合發生更改,則返回true
 421      */
 422     private boolean batchRemove(Collection<?> c, boolean complement) {
 423         final Object[] elementData = this.elementData; //獲取本實例的全部元素
 424         int r = 0, w = 0; //r用於遍歷,w用於記錄相同元素的數量,也用於記錄容器的擴容標記
 425         boolean modified = false; //標誌位
 426         try {
 427             for (; r < size; r++)
 428                 if (c.contains(elementData[r]) == complement) //判斷該元素是否被包含
 429                     elementData[w++] = elementData[r]; //包含則w++
 430         } finally {
 431             // Preserve behavioral compatibility with AbstractCollection,
 432             // even if c.contains() throws.
 433             if (r != size) {//集合有變化
 434                 System.arraycopy(elementData, r, elementData, w, size - r);
 435                 w += size - r;
 436             }
 437             if (w != size) {//容量不相等
 438                 // clear to let GC do its work
 439                 for (int i = w; i < size; i++)
 440                     elementData[i] = null;
 441                 modCount += size - w;
 442                 size = w;
 443                 modified = true; //容量有變化,說明有交集,則返回true
 444             }
 445         }
 446         return modified;
 447     }
 448 
 449     /**
 450      * 將本實例對象寫入流中,實際上只寫入了modCount,size和element[i],其他的內容在實例化時候是沒必要要的,或者可恢復的
 451      */
 452     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
 453         // Write out element count, and any hidden stuff
 454         int expectedModCount = modCount;
 455         s.defaultWriteObject();
 456         // Write out size as capacity for behavioural compatibility with clone()
 457         s.writeInt(size);
 458         // Write out all elements in the proper order.
 459         for (int i=0; i<size; i++) {
 460             s.writeObject(elementData[i]);
 461         }
 462         if (modCount != expectedModCount) {
 463             throw new ConcurrentModificationException();
 464         }
 465     }
 466 
 467     /**
 468      * 從流中讀取本實例對象
 469      */
 470     private void readObject(java.io.ObjectInputStream s)
 471         throws java.io.IOException, ClassNotFoundException {
 472         elementData = EMPTY_ELEMENTDATA
 473         // Read in size, and any hidden stuff
 474         s.defaultReadObject();
 475         // Read in capacity
 476         s.readInt(); // ignored
 477         if (size > 0) {
 478             // be like clone(), allocate array based upon size not capacity
 479             int capacity = calculateCapacity(elementData, size);
 480             SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
 481             ensureCapacityInternal(size);
 482             Object[] a = elementData;
 483             // Read in all elements in the proper order.
 484             for (int i=0; i<size; i++) {
 485                 a[i] = s.readObject();
 486             }
 487         }
 488     }
 489 
 490     /**
 491      * 得到指定長度額本實例的List迭代器
 492      */
 493     public ListIterator<E> listIterator(int index) {
 494         if (index < 0 || index > size)
 495             throw new IndexOutOfBoundsException("Index: "+index);
 496         return new ListItr(index);
 497     }
 498 
 499     /**
 500      * 得到本實例的默認List迭代器
 501      */
 502     public ListIterator<E> listIterator() {
 503         return new ListItr(0);
 504     }
 505 
 506     /**
 507      * 得到本實例的默認迭代器
 508      */
 509     public Iterator<E> iterator() {
 510         return new Itr();
 511     }
 512 
 513     /**
 514      * 內部使用的迭代器,重寫自Iterator接口,爲內部類
 515      */
 516     private class Itr implements Iterator<E> {
 517         int cursor;       // index of next element to return    迭代器指針
 518         int lastRet = -1; // index of last element returned; -1 if no such    末尾標記
 519         int expectedModCount = modCount;
 520         Itr() {}
 521         public boolean hasNext() {
 522             return cursor != size;
 523         }
 524         @SuppressWarnings("unchecked")
 525       //重寫迭代器提供next方法,可能unchecked報錯
 526         public E next() {
 527             checkForComodification();
 528             int i = cursor;
 529             if (i >= size)
 530                 throw new NoSuchElementException();
 531             Object[] elementData = ArrayList.this.elementData;
 532             if (i >= elementData.length)
 533                 throw new ConcurrentModificationException();
 534             cursor = i + 1;
 535             return (E) elementData[lastRet = i];
 536         }
 537       //重寫迭代器提供remove方法
 538         public void remove() {
 539             if (lastRet < 0)
 540                 throw new IllegalStateException();
 541             checkForComodification();
 542             try {
 543                 ArrayList.this.remove(lastRet);
 544                 cursor = lastRet;
 545                 lastRet = -1;
 546                 expectedModCount = modCount;
 547             } catch (IndexOutOfBoundsException ex) {
 548                 throw new ConcurrentModificationException();
 549             }
 550         }
 551 
 552         @Override
 553         @SuppressWarnings("unchecked")//重寫迭代器接口下的forEachRemaining方法,可能unchecked報錯,可以使用lambda迭代
 554         public void forEachRemaining(Consumer<? super E> consumer) {
 555             Objects.requireNonNull(consumer);
 556             final int size = ArrayList.this.size;
 557             int i = cursor;
 558             if (i >= size) {
 559                 return;
 560             }
 561             final Object[] elementData = ArrayList.this.elementData;
 562             if (i >= elementData.length) {
 563                 throw new ConcurrentModificationException();
 564             }
 565             while (i != size && modCount == expectedModCount) {
 566                 consumer.accept((E) elementData[i++]);
 567             }
 568             // update once at end of iteration to reduce heap write traffic
 569             cursor = i;
 570             lastRet = i - 1;
 571             checkForComodification();
 572         }
 573       //校驗modCount修改次數的方法
 574         final void checkForComodification() {
 575             if (modCount != expectedModCount)
 576                 throw new ConcurrentModificationException();
 577         }
 578     }
 579 
 580     /**
 581      * 另外一個內部提供ListItr的迭代器,繼承自上述內部類,實現ListIteraotr接口,本內部類將容許使用固定長度的迭代器
 582      */
 583     private class ListItr extends Itr implements ListIterator<E> {
 584         ListItr(int index) {
 585             super();
 586             cursor = index;
 587         }
 588       //是否有前一個元素
 589         public boolean hasPrevious() {
 590             return cursor != 0;
 591         }
 592       //獲取下一個index
 593         public int nextIndex() {
 594             return cursor;
 595         }
 596       //獲取前一個index
 597         public int previousIndex() {
 598             return cursor - 1;
 599         }
 600       //獲取前一個元素,可能由於unchecked報錯
 601         @SuppressWarnings("unchecked")
 602         public E previous() {
 603             checkForComodification();
 604             int i = cursor - 1;
 605             if (i < 0)
 606                 throw new NoSuchElementException();
 607             Object[] elementData = ArrayList.this.elementData;
 608             if (i >= elementData.length)
 609                 throw new ConcurrentModificationException();
 610             cursor = i;
 611             return (E) elementData[lastRet = i];
 612         }
 613       //對迭代器內當index的元素設置爲指定值
 614         public void set(E e) {
 615             if (lastRet < 0)
 616                 throw new IllegalStateException();
 617             checkForComodification();
 618             try {
 619                 ArrayList.this.set(lastRet, e);
 620             } catch (IndexOutOfBoundsException ex) {
 621                 throw new ConcurrentModificationException();
 622             }
 623         }
 624 
 625         public void add(E e) {
 626             checkForComodification();
 627 
 628             try {
 629                 int i = cursor;
 630                 ArrayList.this.add(i, e);
 631                 cursor = i + 1;
 632                 lastRet = -1;
 633                 expectedModCount = modCount;
 634             } catch (IndexOutOfBoundsException ex) {
 635                 throw new ConcurrentModificationException();
 636             }
 637         }
 638     }
 639 
 640     /**
 641      * 從fromIndex到toIndex拆分數組,內部調用subListRangeCheck方法對本實例進行check
 642      */
 643     public List<E> subList(int fromIndex, int toIndex) {
 644         subListRangeCheck(fromIndex, toIndex, size);
 645         return new SubList(this, 0, fromIndex, toIndex); //調用複寫的內部類,十分巨大
 646     }
 647 /**
 648      * 被內部調用,進行拆分時的參數check校驗
 649      */
 650     static void subListRangeCheck(int fromIndex, int toIndex, int size) {
 651         if (fromIndex < 0)
 652             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
 653         if (toIndex > size)
 654             throw new IndexOutOfBoundsException("toIndex = " + toIndex);
 655         if (fromIndex > toIndex)
 656             throw new IllegalArgumentException("fromIndex(" + fromIndex +") > toIndex(" + toIndex + ")");
 657     }
 658 
 659 /**
 660      * 重寫繼承的AbstractList中的SubList類,對於該類提供和list基本相同的功能進行從新封裝
 661      */
 662     private class SubList extends AbstractList<E> implements RandomAccess {
 663         private final AbstractList<E> parent;
 664         private final int parentOffset;
 665         private final int offset;
 666         int size;
 667       //構造
 668         SubList(AbstractList<E> parent,
 669                 int offset, int fromIndex, int toIndex) {
 670             this.parent = parent;
 671             this.parentOffset = fromIndex;
 672             this.offset = offset + fromIndex;
 673             this.size = toIndex - fromIndex;
 674             this.modCount = ArrayList.this.modCount;
 675         }
 676       //內部類的set方法
 677         public E set(int index, E e) {
 678             rangeCheck(index);
 679             checkForComodification();
 680             E oldValue = ArrayList.this.elementData(offset + index);
 681             ArrayList.this.elementData[offset + index] = e;
 682             return oldValue;
 683         }
 684       //內部類的get方法
 685         public E get(int index) {
 686             rangeCheck(index);
 687             checkForComodification();
 688             return ArrayList.this.elementData(offset + index);
 689         }
 690        //內部類的size方法
 691         public int size() {
 692             checkForComodification();//複用
 693             return this.size;
 694         }
 695       //內部類的add方法
 696         public void add(int index, E e) {
 697             rangeCheckForAdd(index); //複用
 698             checkForComodification();//複用
 699             parent.add(parentOffset + index, e);
 700             this.modCount = parent.modCount;
 701             this.size++;
 702         }
 703       //內部類的remove方法
 704         public E remove(int index) {
 705             rangeCheck(index); //複用
 706             checkForComodification();//複用
 707             E result = parent.remove(parentOffset + index);
 708             this.modCount = parent.modCount;
 709             this.size--;
 710             return result;
 711         }
 712       //從本內部類實例中移除指定範圍的元素並重構本實例
 713         protected void removeRange(int fromIndex, int toIndex) {
 714             checkForComodification();//複用
 715             parent.removeRange(parentOffset + fromIndex,
 716                                parentOffset + toIndex); //使用父類
 717             this.modCount = parent.modCount;
 718             this.size -= toIndex - fromIndex;
 719         }
 720       //內部類的addAll
 721         public boolean addAll(Collection<? extends E> c) {
 722             return addAll(this.size, c);
 723         }
 724       //內部類的addAll,從指定index開始
 725         public boolean addAll(int index, Collection<? extends E> c) {
 726             rangeCheckForAdd(index); //複用
 727             int cSize = c.size();
 728             if (cSize==0)
 729                 return false;
 730             checkForComodification();//複用
 731             parent.addAll(parentOffset + index, c);
 732             this.modCount = parent.modCount;
 733             this.size += cSize;
 734             return true;
 735         }
 736       //內部類的迭代器
 737         public Iterator<E> iterator() {
 738             return listIterator();
 739         }
 740       //內部類的迭代器,被內部調用
 741         public ListIterator<E> listIterator(final int index) {
 742             checkForComodification();//複用
 743             rangeCheckForAdd(index); //複用
 744             final int offset = this.offset;
 745             return new ListIterator<E>() {
 746                 int cursor = index;
 747                 int lastRet = -1;
 748                 int expectedModCount = ArrayList.this.modCount;
 749                 public boolean hasNext() {
 750                     return cursor != SubList.this.size;
 751                 }
 752             //內部類的迭代器的next
 753                 @SuppressWarnings("unchecked")
 754                 public E next() {
 755                     checkForComodification();
 756                     int i = cursor;
 757                     if (i >= SubList.this.size)
 758                         throw new NoSuchElementException();
 759                     Object[] elementData = ArrayList.this.elementData;
 760                     if (offset + i >= elementData.length)
 761                         throw new ConcurrentModificationException();
 762                     cursor = i + 1;
 763                     return (E) elementData[offset + (lastRet = i)];
 764                 }
 765             //內部類的迭代器的判斷是否有前一個元素
 766                 public boolean hasPrevious() {
 767                     return cursor != 0;
 768                 }
 769             //內部類的獲取前一個元素
 770                 @SuppressWarnings("unchecked")
 771                 public E previous() {
 772                     checkForComodification();
 773                     int i = cursor - 1;
 774                     if (i < 0)
 775                         throw new NoSuchElementException();
 776                     Object[] elementData = ArrayList.this.elementData;
 777                     if (offset + i >= elementData.length)
 778                         throw new ConcurrentModificationException();
 779                     cursor = i;
 780                     return (E) elementData[offset + (lastRet = i)];
 781                 }
 782             //剩餘元素的迭代,可使用lambda表達式進行遍歷
 783                 @SuppressWarnings("unchecked")
 784                 public void forEachRemaining(Consumer<? super E> consumer) {
 785                     Objects.requireNonNull(consumer);
 786                     final int size = SubList.this.size;
 787                     int i = cursor;
 788                     if (i >= size) {
 789                         return;
 790                     }
 791                     final Object[] elementData = ArrayList.this.elementData;
 792                     if (offset + i >= elementData.length) {
 793                         throw new ConcurrentModificationException();
 794                     }
 795                     while (i != size && modCount == expectedModCount) {
 796                         consumer.accept((E) elementData[offset + (i++)]);
 797                     }
 798                     // update once at end of iteration to reduce heap write traffic
 799                     lastRet = cursor = i;
 800                     checkForComodification();
 801                 }
 802             //內部類的迭代器中獲取下一個元素的index
 803                 public int nextIndex() {
 804                     return cursor;
 805                 }
 806             //內部類的迭代器中獲取上一個元素的index
 807                 public int previousIndex() {
 808                     return cursor - 1;
 809                 }
 810             //內部類的迭代器中移除當前元素
 811                 public void remove() {
 812                     if (lastRet < 0)
 813                         throw new IllegalStateException();
 814                     checkForComodification();
 815                     try {
 816                         SubList.this.remove(lastRet);
 817                         cursor = lastRet;
 818                         lastRet = -1;
 819                         expectedModCount = ArrayList.this.modCount;
 820                     } catch (IndexOutOfBoundsException ex) {
 821                         throw new ConcurrentModificationException();
 822                     }
 823                 }
 824             //內部類的迭代器對當前元素設置成指定值
 825                 public void set(E e) {
 826                     if (lastRet < 0)
 827                         throw new IllegalStateException();
 828                     checkForComodification();
 829                     try {
 830                         ArrayList.this.set(offset + lastRet, e);
 831                     } catch (IndexOutOfBoundsException ex) {
 832                         throw new ConcurrentModificationException();
 833                     }
 834                 }
 835             //內部類的迭代器中add方法添加元素到迭代器末尾
 836                 public void add(E e) {
 837                     checkForComodification();
 838                     try {
 839                         int i = cursor;
 840                         SubList.this.add(i, e);
 841                         cursor = i + 1;
 842                         lastRet = -1;
 843                         expectedModCount = ArrayList.this.modCount;
 844                     } catch (IndexOutOfBoundsException ex) {
 845                         throw new ConcurrentModificationException();
 846                     }
 847                 }
 848             //內部類的modCount校驗
 849                 final void checkForComodification() {
 850                     if (expectedModCount != ArrayList.this.modCount)
 851                         throw new ConcurrentModificationException();
 852                 }
 853             };
 854         }
 855       
 856 /**
 857          * 內部類的拆分list的方法
 858          */
 859         public List<E> subList(int fromIndex, int toIndex) {
 860             subListRangeCheck(fromIndex, toIndex, size);
 861             return new SubList(this, offset, fromIndex, toIndex);
 862         }
 863       /**
 864             * 內部類的index越界檢查方法
 865          */
 866         private void rangeCheck(int index) {
 867             if (index < 0 || index >= this.size)
 868                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 869         }
 870       /**
 871             * 同上,add和addAll專用
 872          */
 873         private void rangeCheckForAdd(int index) {
 874             if (index < 0 || index > this.size)
 875                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 876         }
 877       /**
 878             * 內部類rangeCheckForAdd中拋異常調用,寫明index和size
 879          */
 880         private String outOfBoundsMsg(int index) {
 881             return "Index: "+index+", Size: "+this.size;
 882         }
 883       /**
 884             * 內部類的modCount校驗
 885          */
 886         private void checkForComodification() {
 887             if (ArrayList.this.modCount != this.modCount)
 888                 throw new ConcurrentModificationException();
 889         }
 890       /**
 891             * 內部類的分離迭代器函數,調用ArrayList的ArrayListSpliterator內部類的構造器
 892          */
 893         public Spliterator<E> spliterator() {
 894             checkForComodification();
 895             return new ArrayListSpliterator<E>(ArrayList.this, offset, offset + this.size, this.modCount);
 896         }
 897     }
 898 
 899 /**
 900      * 重寫繼承的forEach方法,用於迭代
 901      */
 902     @Override
 903     public void forEach(Consumer<? super E> action) {
 904         Objects.requireNonNull(action);
 905         final int expectedModCount = modCount;
 906         @SuppressWarnings("unchecked")
 907         final E[] elementData = (E[]) this.elementData;
 908         final int size = this.size;
 909         for (int i=0; modCount == expectedModCount && i < size; i++) {
 910             action.accept(elementData[i]);
 911         }
 912         if (modCount != expectedModCount) {
 913             throw new ConcurrentModificationException();
 914         }
 915     }
 916 
 917     /**
 918      * jd1.8更新
 919      * 重寫自父類,分離數組,默認使用本類內容,從0-末尾,
 920      */
 921     @Override
 922     public Spliterator<E> spliterator() {
 923         return new ArrayListSpliterator<>(this, 0, -1, 0);
 924     }
 925 
 926     /**
 927      * jd1.8更新
 928      * 重寫自父類,實現Spliterator接口
 929      * 本類用於分離ArrayList,前提是ArrayList暫定是不變的,不然將可能出現線程錯誤
 930      */
 931     static final class ArrayListSpliterator<E> implements Spliterator<E> {
 932 
 933         private final ArrayList<E> list;
 934         private int index; // current index, modified on advance/split
 935         private int fence; // -1 until used; then one past last index
 936         private int expectedModCount; // initialized when fence set
 937 
 938        /**
 939          * 內部類ArrayListSpliterator的構造器
 940          */
 941         ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
 942                              int expectedModCount) {
 943             this.list = list; // OK if null unless traversed
 944             this.index = origin;
 945             this.fence = fence;
 946             this.expectedModCount = expectedModCount;
 947         }
 948        /**
 949          * 內部類ArrayListSpliterator中不少方法都使用的初始化方法
 950          */
 951         private int getFence() { // initialize fence to size on first use
 952             int hi; // (a specialized variant appears in method forEach)
 953             ArrayList<E> lst;
 954             if ((hi = fence) < 0) {
 955                 if ((lst = list) == null)
 956                     hi = fence = 0;
 957                 else {
 958                     expectedModCount = lst.modCount;
 959                     hi = fence = lst.size;
 960                 }
 961             }
 962             return hi;
 963         }
 964        /**
 965          * 內部類ArrayListSpliterator的拆分arraylist方法,不保證結果正確
 966          */
 967         public ArrayListSpliterator<E> trySplit() {
 968             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
 969             return (lo >= mid) ? null : // divide range in half unless too small
 970                 new ArrayListSpliterator<E>(list, lo, index = mid, expectedModCount);
 971         }
 972 
 973        /**
 974          * 內部類ArrayListSpliterator的預拆分?嘗試是否可以拆分
 975          */
 976         public boolean tryAdvance(Consumer<? super E> action) {
 977             if (action == null)
 978                 throw new NullPointerException();
 979             int hi = getFence(), i = index;
 980             if (i < hi) {
 981                 index = i + 1;
 982                 @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
 983                 action.accept(e);
 984                 if (list.modCount != expectedModCount)
 985                     throw new ConcurrentModificationException();
 986                 return true;
 987             }
 988             return false;
 989         }
 990 
 991        /**
 992          * 內部類ArrayListSpliterator迭代
 993          */
 994         public void forEachRemaining(Consumer<? super E> action) {
 995             int i, hi, mc; // hoist accesses and checks from loop
 996             ArrayList<E> lst; Object[] a;
 997             if (action == null)
 998                 throw new NullPointerException();
 999             if ((lst = list) != null && (a = lst.elementData) != null) {
1000                 if ((hi = fence) < 0) {
1001                     mc = lst.modCount;
1002                     hi = lst.size;
1003                 }
1004                 else
1005                     mc = expectedModCount;
1006                 if ((i = index) >= 0 && (index = hi) <= a.length) {
1007                     for (; i < hi; ++i) {
1008                         @SuppressWarnings("unchecked") E e = (E) a[i];
1009                         action.accept(e);
1010                     }
1011                     if (lst.modCount == mc)
1012                         return;
1013                 }
1014             }
1015             throw new ConcurrentModificationException();
1016         }
1017       //內部類ArrayListSpliterator的size預估
1018         public long estimateSize() {
1019             return (long) (getFence() - index);
1020         }
1021 
1022       //分離參數初始化
1023         public int characteristics() {
1024             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1025         }
1026     }
1027 
1028     /**
1029      * 重寫自父類,使用重寫的filter接口進行篩選,符合條件的則移除
1030      */
1031     @Override
1032     public boolean removeIf(Predicate<? super E> filter) {
1033         Objects.requireNonNull(filter);
1034         // figure out which elements are to be removed
1035         // any exception thrown from the filter predicate at this stage
1036         // will leave the collection unmodified
1037         int removeCount = 0;
1038         final BitSet removeSet = new BitSet(size);
1039         final int expectedModCount = modCount;
1040         final int size = this.size;
1041         for (int i=0; modCount == expectedModCount && i < size; i++) {
1042             @SuppressWarnings("unchecked")
1043             final E element = (E) elementData[i];
1044             if (filter.test(element)) {
1045                 removeSet.set(i);
1046                 removeCount++;
1047             }
1048         }
1049         if (modCount != expectedModCount) {
1050             throw new ConcurrentModificationException();
1051         }
1052 
1053         // shift surviving elements left over the spaces left by removed elements
1054         final boolean anyToRemove = removeCount > 0;
1055         if (anyToRemove) {
1056             final int newSize = size - removeCount;
1057             for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1058                 i = removeSet.nextClearBit(i);
1059                 elementData[j] = elementData[i];
1060             }
1061             for (int k=newSize; k < size; k++) {
1062                 elementData[k] = null;  // Let gc do its work
1063             }
1064             this.size = newSize;
1065             if (modCount != expectedModCount) {
1066                 throw new ConcurrentModificationException();
1067             }
1068             modCount++;
1069         }
1070         return anyToRemove;
1071     }
1072 
1073    /**
1074      * 重寫自父類,使用重寫的operator接口進行替代本實例中匹配的元素
1075      */
1076     @Override
1077     @SuppressWarnings("unchecked")
1078     public void replaceAll(UnaryOperator<E> operator) {
1079         Objects.requireNonNull(operator);
1080         final int expectedModCount = modCount;
1081         final int size = this.size;
1082         for (int i=0; modCount == expectedModCount && i < size; i++) {
1083             elementData[i] = operator.apply((E) elementData[i]);
1084         }
1085         if (modCount != expectedModCount) {
1086             throw new ConcurrentModificationException();
1087         }
1088         modCount++;
1089     }
1090 
1091    /**
1092      * 重寫自父類,使用comparator接口對本實例進行排序
1093      */
1094     @Override
1095     @SuppressWarnings("unchecked")
1096     public void sort(Comparator<? super E> c) {
1097         final int expectedModCount = modCount;
1098         Arrays.sort((E[]) elementData, 0, size, c);
1099         if (modCount != expectedModCount) {
1100             throw new ConcurrentModificationException();
1101         }
1102         modCount++;
1103     }
1104 }

 

 

  本篇註釋前偏,只是粗略的瞭解,中篇 和 後篇 將對其中的使用進行總結和舉例。

 

以上!

相關文章
相關標籤/搜索