1. 程式人生 > >Java 集合系列04之 fail-fast總結(通過ArrayList來說明fail-fast的原理、解決辦法)

Java 集合系列04之 fail-fast總結(通過ArrayList來說明fail-fast的原理、解決辦法)

  1 package java.util;
  2 
  3 public class ArrayList<E> extends AbstractList<E>
  4         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  5 {
  6 
  7     ...
  8 
  9     // list中容量變化時,對應的同步函式
 10     public void ensureCapacity(int minCapacity) {
 11
modCount++; 12 int oldCapacity = elementData.length; 13 if (minCapacity > oldCapacity) { 14 Object oldData[] = elementData; 15 int newCapacity = (oldCapacity * 3)/2 + 1; 16 if (newCapacity < minCapacity) 17 newCapacity = minCapacity;
18 // minCapacity is usually close to size, so this is a win: 19 elementData = Arrays.copyOf(elementData, newCapacity); 20 } 21 } 22 23 24 // 新增元素到佇列最後 25 public boolean add(E e) { 26 // 修改modCount 27 ensureCapacity(size + 1); //
Increments modCount!! 28 elementData[size++] = e; 29 return true; 30 } 31 32 33 // 新增元素到指定的位置 34 public void add(int index, E element) { 35 if (index > size || index < 0) 36 throw new IndexOutOfBoundsException( 37 "Index: "+index+", Size: "+size); 38 39 // 修改modCount 40 ensureCapacity(size+1); // Increments modCount!! 41 System.arraycopy(elementData, index, elementData, index + 1, 42 size - index); 43 elementData[index] = element; 44 size++; 45 } 46 47 // 新增集合 48 public boolean addAll(Collection<? extends E> c) { 49 Object[] a = c.toArray(); 50 int numNew = a.length; 51 // 修改modCount 52 ensureCapacity(size + numNew); // Increments modCount 53 System.arraycopy(a, 0, elementData, size, numNew); 54 size += numNew; 55 return numNew != 0; 56 } 57 58 59 // 刪除指定位置的元素 60 public E remove(int index) { 61 RangeCheck(index); 62 63 // 修改modCount 64 modCount++; 65 E oldValue = (E) elementData[index]; 66 67 int numMoved = size - index - 1; 68 if (numMoved > 0) 69 System.arraycopy(elementData, index+1, elementData, index, numMoved); 70 elementData[--size] = null; // Let gc do its work 71 72 return oldValue; 73 } 74 75 76 // 快速刪除指定位置的元素 77 private void fastRemove(int index) { 78 79 // 修改modCount 80 modCount++; 81 int numMoved = size - index - 1; 82 if (numMoved > 0) 83 System.arraycopy(elementData, index+1, elementData, index, 84 numMoved); 85 elementData[--size] = null; // Let gc do its work 86 } 87 88 // 清空集合 89 public void clear() { 90 // 修改modCount 91 modCount++; 92 93 // Let gc do its work 94 for (int i = 0; i < size; i++) 95 elementData[i] = null; 96 97 size = 0; 98 } 99 100 ... 101 }