HashMap源碼和併發異常問題分析

  1. 要點源碼分析

    1. HashMap容許鍵值對爲null;HashTable則不容許,會報空指針異常;
              HashMap<String, String> map= new HashMap<>(2);
              map.put(null,null);
              map.put("1",null);
    2. HashMap初始容量是16,擴容方式爲2N:

      static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16,默認大小
          //元素的位置要麼是在原位置,要麼是在原位置再移動2次冪的位置
          final Node<K,V>[] resize() {
              Node<K,V>[] oldTab = table;//原先的數組,舊數組
              int oldCap = (oldTab == null) ? 0 : oldTab.length;//舊數組長度
              int oldThr = threshold;//閥值
              int newCap, newThr = 0;
              if (oldCap > 0) {//數組已經存在不須要進行初始化
                  if (oldCap >= MAXIMUM_CAPACITY) {//舊數組容量超過最大容量限制,不擴容直接返回舊數組
                      threshold = Integer.MAX_VALUE;
                      return oldTab;
                  }
                  //進行2倍擴容後的新數組容量小於最大容量和舊數組長度大於等於16
                  else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                           oldCap >= DEFAULT_INITIAL_CAPACITY)
                      newThr = oldThr << 1; // double threshold,從新計算閥值爲原來的2倍
              }
              //初始化數組
              else if (oldThr > 0) // initial capacity was placed in threshold,有閥值,初始容量的值爲閥值
                  newCap = oldThr;
              else {               // zero initial threshold signifies using defaults,沒有閥值
                  newCap = DEFAULT_INITIAL_CAPACITY;//初始化的默認容量
                  newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//從新計算閥值
              }
              //有閥值,定義了新數組的容量,從新計算閥值
              if (newThr == 0) {
                  float ft = (float)newCap * loadFactor;
                  newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                            (int)ft : Integer.MAX_VALUE);
              }
              threshold = newThr;//賦予新閥值
              @SuppressWarnings({"rawtypes","unchecked"})
                  Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//建立新數組
              table = newTab;
              if (oldTab != null) {//若是舊數組有數據,進行數據移動,若是沒有數據,返回一個空數組
                  for (int j = 0; j < oldCap; ++j) {//對舊數組進行遍歷
                      Node<K,V> e;
                      if ((e = oldTab[j]) != null) {
                          oldTab[j] = null;//將舊數組的所屬位置的舊元素清空
                          if (e.next == null)//當前節點是在數組上,後面沒有鏈表,從新計算槽位
                              newTab[e.hash & (newCap - 1)] = e;
                          else if (e instanceof TreeNode)//當前節點是紅黑樹,紅黑樹重定位
                              ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                          else { // preserve order,當前節點是鏈表
                              Node<K,V> loHead = null, loTail = null;
                              Node<K,V> hiHead = null, hiTail = null;
                              Node<K,V> next;
                              //遍歷鏈表
                              do {
                                  next = e.next;
                                  if ((e.hash & oldCap) == 0) {//不須要移位
                                      if (loTail == null)//頭節點是空的
                                          loHead = e;//頭節點放置當前遍歷到的元素
                                      else
                                          loTail.next = e;//當前元素放到尾節點的後面
                                      loTail = e;//尾節點重置爲當前元素
                                  }
                                  else {//須要移位
                                      if (hiTail == null)//頭節點是空的
                                          hiHead = e;//頭節點放置當前遍歷到的元素
                                      else
                                          hiTail.next = e;//當前元素放到尾節點的後面
                                      hiTail = e;//尾節點重置爲當前元素
                                  }
                              } while ((e = next) != null);
                              if (loTail != null) {//不須要移位
                                  loTail.next = null;
                                  newTab[j] = loHead;//原位置
                              }
                              if (hiTail != null) {
                                  hiTail.next = null;
                                  newTab[j + oldCap] = hiHead;//移動到當前hash槽位 + oldCap的位置,即在原位置再移動2次冪的位置
                              }
                          }
                      }
                  }
              }
              return newTab;
          }
      1. 當前節點是數組,後面沒有鏈表,從新計算槽位:位與操做的效率比效率高

             定位槽位:e.hash & (newCap - 1)
             咱們用長度16, 待插入節點的hash值爲21舉例:
             (1)取餘: 21 % 16 = 5
             (2)位與:
             21: 0001 0101
                     &
             15: 0000 1111
             5:  0000 0101
      2. 遍歷鏈表,對鏈表節點進行移位判斷:(e.hash & oldCap) == 0

             好比oldCap=8,hash是3,11,19,27時,
             (1)JDK1.8中(e.hash & oldCap)的結果是0,8,0,8,這樣3,19組成新的鏈表,index爲3;而11,27組成新的鏈表,新分配的index爲3+8;
             (2)JDK1.7中是(e.hash & newCap-1),newCap是oldCap的兩倍,也就是3,11,19,27對(16-1)與計算,也是0,8,0,8,但因爲是使用了單鏈表的頭插入方式,即同一位置上新元素總會被放在鏈表的頭部位置;這樣先放在一個索引上的元素終會被放到Entry鏈的尾部(若是發生了hash衝突的話),這樣index爲3的鏈表是19,3,index爲3+8的鏈表是 27,11。
             也就是說1.7中通過resize後數據的順序變成了倒敘,而1.8沒有改變順序。
    3. 構造方法:

      public HashMap() {//默認初始容量爲16,加載因子爲0.75
              this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
          }
          public HashMap(int initialCapacity) {//指定初始容量爲initialCapacity
              this(initialCapacity, DEFAULT_LOAD_FACTOR);
          }
          static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
      
          //當size到達threshold這個閾值時會擴容,下一次擴容的值,根據capacity * load factor進行計算,
          int threshold;
          /**因爲HashMap的capacity都是2的冪,所以這個方法用於找到大於等於initialCapacity的最小的2的冪(initialCapacity若是就是2的冪,則返回的仍是這個數)
           * 經過5次無符號移位運算以及或運算獲得:
           *    n第一次右移一位時,至關於將最高位的1右移一位,再和原來的n取或,就將最高位和次高位都變成1,也就是兩個1;
           *    第二次右移兩位時,將最高的兩個1向右移了兩位,取或後獲得四個1;
           *    依次類推,右移16位再取或就能獲得32個1;
           *    最後經過加一進位獲得2^n。
           * 好比initialCapacity = 10 ,那就返回16, initialCapacity = 17,那麼就返回32
           *    10的二進制是1010,減1就是1001
           *    第一次右移取或: 1001 | 0100 = 1101 ;
           *    第二次右移取或: 1101 | 0011 = 1111 ;
           *    第三次右移取或: 1111 | 0000 = 1111 ;
           *    第四次第五次同理
           *    最後獲得 n = 1111,返回值是 n+1 = 2 ^ 4 = 16 ;
           * 讓cap-1再賦值給n的目的是另找到的目標值大於或等於原值。這是爲了防止,cap已是2的冪。若是cap已是2的冪,又沒有執行這個減1操做,則執行完後面的幾條無符號右移操做以後,返回的capacity將是這個cap的2倍。
           * 例如十進制數值8,二進制爲1000,若是不對它減1而直接操做,將獲得答案10000,即16。顯然不是結果。減1後二進制爲111,再進行操做則會獲得原來的數值1000,即8。
           * 問題:tableSizeFor()最後賦值給threshold,但threshold是根據capacity * load factor進行計算的,這是否是有問題?
           * 注意:在構造方法中,並無對table這個成員變量進行初始化,table的初始化被推遲到了put方法中,在put方法中會對threshold從新計算。
           * 問題:既然put會從新計算threshold,那麼在構造初始化threshold的做用是什麼?
           * 答:在put時,會對table進行初始化,若是threshold大於0,會把threshold看成數組的長度進行table的初始化,不然建立的table的長度爲16。
           */
          static final int tableSizeFor(int cap) {
              int n = cap - 1;
              n |= n >>> 1;
              n |= n >>> 2;
              n |= n >>> 4;
              n |= n >>> 8;
              n |= n >>> 16;
              return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
          }
          public HashMap(int initialCapacity, float loadFactor) {//指定初始容量和加載因子
              if (initialCapacity < 0)
                  throw new IllegalArgumentException("Illegal initial capacity: " +
                                                     initialCapacity);
              if (initialCapacity > MAXIMUM_CAPACITY)//大於最大容量,設置爲最大容量
                  initialCapacity = MAXIMUM_CAPACITY;
              if (loadFactor <= 0 || Float.isNaN(loadFactor))//加載因子小於等於0或爲NaN拋出異常
                  throw new IllegalArgumentException("Illegal load factor: " +
                                                     loadFactor);
              this.loadFactor = loadFactor;
              this.threshold = tableSizeFor(initialCapacity);//閥值
          }
  2. put/get/remove/containsKey/containsValue/putAll/clear/replace源碼分析

    1. put:

          public V put(K key, V value) {
              return putVal(hash(key), key, value, false, true);
          }
      1. hash計算:key的hash值高16位不變,低16位與高16位異或做爲key的最終hash值。(h >>> 16,表示無符號右移16位,高位補0,任何數跟0異或都是其自己,所以key的hash值高16位不變。)

        static final int hash(Object key) {
                int h;
                return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
            }

        • 之因此要無符號右移16位,是跟table的下標有關,上面的擴容中對數組槽位的從新計算方式是:e.hash & (newCap - 1),假如newCap=16,從下圖能夠看出:table的下標僅與hash值的低n位有關,hash值的高位都被與操做置爲0了,只有hash值的低4位參與了運算。
      2.  putVal:

        final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                           boolean evict) {
                Node<K,V>[] tab; Node<K,V> p; int n, i;
                //沒有數組能夠存放元素進行初始化
                if ((tab = table) == null || (n = tab.length) == 0)
                    n = (tab = resize()).length;
                //計算的槽位爲空,元素存放到該位置
                if ((p = tab[i = (n - 1) & hash]) == null)
                    tab[i] = newNode(hash, key, value, null);
                else {//hash衝突了
                    Node<K,V> e; K k;
                    if (p.hash == hash &&
                        ((k = p.key) == key || (key != null && key.equals(k))))
                        e = p;//同一個key,對value進行覆蓋
                    else if (p instanceof TreeNode)//樹節點
                        e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                    else {//鏈表
                        // 循環,直到鏈表中的某個節點爲null,或者某個節點hash值和給定的hash值一致且key也相同,則中止循環。
                        for (int binCount = 0; ; ++binCount) {
                            if ((e = p.next) == null) {//next爲空,將添加的元素置爲next
                                p.next = newNode(hash, key, value, null);
                                //鏈表長度達到了閥值TREEIFY_THRESHOLD=8,即鏈表長度達到了7
                                if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                    // 若是鏈表長度達到了8,且數組長度小於64,那麼就從新散列resize(),若是大於64,則建立紅黑樹
                                    treeifyBin(tab, hash);
                                //結束循環
                                break;
                            }
                            //節點hash值和給定的hash值一致且key也相同,中止循環
                            if (e.hash == hash &&
                                ((k = e.key) == key || (key != null && key.equals(k))))
                                break;
                            //若是給定的hash值不一樣或者key不一樣。將next值賦給p,爲下次循環作鋪墊。即結束當前節點,對下一節點進行判斷
                            p = e;
                        }
                    }
                    //若是e不是null,該元素存在了(也就是key相等)
                    if (e != null) { // existing mapping for key
                        // 取出該元素的值
                        V oldValue = e.value;
                        // 若是 onlyIfAbsent 是 true,就不用改變已有的值;若是是false(默認),或者value是null,將新的值替換老的值
                        if (!onlyIfAbsent || oldValue == null)
                            e.value = value;
                        //什麼都不作
                        afterNodeAccess(e);
                        //返回舊值
                        return oldValue;
                    }
                }
                //修改計數器+1,爲迭代服務
                ++modCount;
                //達到了閥值,須要擴容
                if (++size > threshold)
                    resize();
                //什麼都不作
                afterNodeInsertion(evict);
                //返回null
                return null;
            }
    2. get:

          public V get(Object key) {
              Node<K,V> e;
              return (e = getNode(hash(key), key)) == null ? null : e.value;
          }
          final Node<K,V> getNode(int hash, Object key) {
              Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
              //數組不爲null,數組長度大於0,根據hash計算出來的槽位的元素不爲null
              if ((tab = table) != null && (n = tab.length) > 0 &&
                  (first = tab[(n - 1) & hash]) != null) {
                  //查找的元素在數組中,返回該元素
                  if (first.hash == hash && // always check first node
                      ((k = first.key) == key || (key != null && key.equals(k))))
                      return first;
                  if ((e = first.next) != null) {//查找的元素在鏈表或紅黑樹中
                      if (first instanceof TreeNode)//元素在紅黑樹中,返回該元素
                          return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                      do {//遍歷鏈表,元素在鏈表中,返回該元素
                          if (e.hash == hash &&
                              ((k = e.key) == key || (key != null && key.equals(k))))
                              return e;
                      } while ((e = e.next) != null);
                  }
              }
              //找不到返回null
              return null;
          } 
    3. remove:

          public V remove(Object key) {
              Node<K,V> e;
              return (e = removeNode(hash(key), key, null, false, true)) == null ?
                  null : e.value;
          }
          final Node<K,V> removeNode(int hash, Object key, Object value,
                                     boolean matchValue, boolean movable) {
              Node<K,V>[] tab; Node<K,V> p; int n, index;
              //數組不爲null,數組長度大於0,要刪除的元素計算的槽位有元素
              if ((tab = table) != null && (n = tab.length) > 0 &&
                  (p = tab[index = (n - 1) & hash]) != null) {
                  Node<K,V> node = null, e; K k; V v;
                  //當前元素在數組中
                  if (p.hash == hash &&
                      ((k = p.key) == key || (key != null && key.equals(k))))
                      node = p;
                  //元素在紅黑樹或鏈表中
                  else if ((e = p.next) != null) {
                      if (p instanceof TreeNode)//是樹節點,從樹種查找節點
                          node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                      else {
                          do {
                              //hash相同,而且key相同,找到節點並結束
                              if (e.hash == hash &&
                                  ((k = e.key) == key ||
                                   (key != null && key.equals(k)))) {
                                  node = e;
                                  break;
                              }
                              p = e;
                          } while ((e = e.next) != null);//遍歷鏈表
                      }
                  }
                  //找到節點了,而且值也相同
                  if (node != null && (!matchValue || (v = node.value) == value ||
                                       (value != null && value.equals(v)))) {
                      if (node instanceof TreeNode)//是樹節點,從樹中移除
                          ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                      else if (node == p)//節點在數組中,
                          tab[index] = node.next;//當前槽位置爲null,node.next爲null
                      else//節點在鏈表中
                          p.next = node.next;//將節點刪除
                      ++modCount;//修改計數器+1,爲迭代服務
                      --size;//數量-1
                      afterNodeRemoval(node);//什麼都不作
                      return node;//返回刪除的節點
                  }
              }
              return null;
          }
    4. containsKey:

          public boolean containsKey(Object key) {
              return getNode(hash(key), key) != null;//查看上面的get的getNode
          }
    5. containsValue:

          public boolean containsValue(Object value) {
              Node<K,V>[] tab; V v;
              //數組不爲null而且長度大於0
              if ((tab = table) != null && size > 0) {
                  for (int i = 0; i < tab.length; ++i) {//對數組進行遍歷
                      for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                          //當前節點的值等價查找的值,返回true
                          if ((v = e.value) == value ||
                              (value != null && value.equals(v)))
                              return true;
                      }
                  }
              }
              return false;//找不到返回false
          }
    6. putAll:

          public void putAll(Map<? extends K, ? extends V> m) {
              putMapEntries(m, true);
          }
          final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
              int s = m.size();//得到插入整個m的元素數量
              if (s > 0) {
                  if (table == null) { // pre-size,當前map尚未初始化數組
                      float ft = ((float)s / loadFactor) + 1.0F;//m的容量
                      //判斷容量是否大於最大值MAXIMUM_CAPACITY
                      int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                               (int)ft : MAXIMUM_CAPACITY);
                      //容量達到了閥值,好比插入的m的定義容量是16,但當前map的閥值是12,須要對當前map進行從新計算閥值
                      if (t > threshold)
                          threshold = tableSizeFor(t);//從新計算閥值
                  }
                  else if (s > threshold)//存放的數量達到了閥值,擴容
                      resize();
                  //對m進行遍歷,放到當前map中
                  for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                      K key = e.getKey();
                      V value = e.getValue();
                      putVal(hash(key), key, value, false, evict);
                  }
              }
          }
    7. clear:

          public void clear() {
              Node<K,V>[] tab;
              modCount++;//修改計數器+1,爲迭代服務
              if ((tab = table) != null && size > 0) {
                  size = 0;//將數組的元素格式置爲0,而後遍歷數組,將每一個槽位的元素置爲null
                  for (int i = 0; i < tab.length; ++i)
                      tab[i] = null;
              }
          }
    8. replace:

          public boolean replace(K key, V oldValue, V newValue) {
              Node<K,V> e; V v;
              //根據hash計算獲得槽位的節點不爲null,而且節點的值等於舊值
              if ((e = getNode(hash(key), key)) != null &&
                  ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
                  e.value = newValue;//覆蓋舊值
                  afterNodeAccess(e);
                  return true;
              }
              return false;
          }
      
          public V replace(K key, V value) {
              Node<K,V> e;
              //根據hash計算獲得槽位的節點不爲null
              if ((e = getNode(hash(key), key)) != null) {
                  V oldValue = e.value;//節點的舊值
                  e.value = value;//覆蓋舊值
                  afterNodeAccess(e);
                  return oldValue;//返回舊值
              }
              return null;//找不到key對應的節點
          }
  3. 問題分析

    1. HashMap遍歷中修改出現ConcurrentModificationException併發修改異常解析:

      Exception in thread "main" java.util.ConcurrentModificationException
          at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
          at java.util.HashMap$KeyIterator.next(HashMap.java:1466)
      1. 遍歷的幾種方式:
        //====1=====
            for (String key : map.keySet()) {
                System.out.println(map.get(key));
                map.remove(key);
            }
            //編譯後
            Iterator var2 = map.keySet().iterator();
            while(var2.hasNext()) {
                String key = (String)var2.next();
                System.out.println((String)map.get(key));
                map.remove(key);
            }
            //====2=====
            for(Map.Entry<String,String> entry:map.entrySet()){
                System.out.println(entry.getKey()+":"+entry.getValue());
                map.remove(entry.getKey());
            }    
            //編譯後
            Iterator var2 = map.entrySet().iterator();
            while(var2.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var2.next();
                System.out.println((String)entry.getKey() + ":" + (String)entry.getValue());
                map.remove(entry.getKey());
            }  
            //====3=====
            for(String values:map.values()){
                System.out.println(values);
                map.remove(values);
            }
            //編譯後
            Iterator var2 = map.values().iterator();
            while(var2.hasNext()) {
                String values = (String)var2.next();
                System.out.println(values);
                map.remove(values);
            }
      2. 解析:從上面編譯後的代碼能夠看到,hasNext -> next
        //====1=====
            final class KeySet extends AbstractSet<K> {
                public final Iterator<K> iterator()     { return new KeyIterator(); }
            }
            final class KeyIterator extends HashIterator
                implements Iterator<K> {
                public final K next() { return nextNode().key; }//調用HashIterator的nextNode()
            }
            abstract class HashIterator {
                HashIterator() {//構造方法
                    expectedModCount = modCount;//將當前的指望計數器值進行賦值
                    Node<K,V>[] t = table;//獲得數組
                    current = next = null;//當前節點和下一個節點爲null
                    index = 0;//當前節點的下標
                    //經過while循環,獲得數組中的第一個不爲空的元素下標以及值,並將此元素值賦給next
                    if (t != null && size > 0) { // advance to first entry
                        do {} while (index < t.length && (next = t[index++]) == null);
                    }
                }
                public final boolean hasNext() {
                    return next != null;
                }
                //返回下一節點
                final Node<K,V> nextNode() {
                    Node<K,V>[] t;
                    Node<K,V> e = next;//返回的節點
                    //問題在這裏,計數器跟指望的計數器不一致致使異常,每次的remove和put都會從新對計數器進行+1,但指望的計數器在HashIterator初始化時就定義了,後面的調用HashIterator的nextNode就沒有從新對指望的計數器進行重置
                    if (modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                    if (e == null)//節點爲null返回異常
                        throw new NoSuchElementException();
                    //當前節點遍歷結束,while遍歷其餘節點的,將下一節點賦予next,直到數組爲空結束
                    if ((next = (current = e).next) == null && (t = table) != null) {
                        do {} while (index < t.length && (next = t[index++]) == null);
                    }
                    return e;
                }
            }
            //====2=====
            final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
                public final Iterator<Map.Entry<K,V>> iterator() {
                    return new EntryIterator();
                }
            }
            final class EntryIterator extends HashIterator
                implements Iterator<Map.Entry<K,V>> {
                public final Map.Entry<K,V> next() { return nextNode(); }//調用HashIterator的nextNode()
            }
            //====3=====
            final class Values extends AbstractCollection<V> {
                public final Iterator<V> iterator()     { return new ValueIterator(); }
            }
            final class ValueIterator extends HashIterator
                implements Iterator<V> {
                public final V next() { return nextNode().value; }//調用HashIterator的nextNode()
            }
      3. 解決方式:從下面的代碼能夠看出,將map.keySet轉換爲ArrayList後,獲取到的是ArrayList的迭代器,這樣迭代next和刪除remove操做的是不一樣的對象(ArrayList和HashMap),沒有併發修改異常,上面的三種方式迭代和刪除的對象都是HashMap,致使出現問題。

                ArrayList<String> strings = new ArrayList<>(map.keySet());
                for(String key : strings){
                    System.out.println(map.get(key));
                    System.out.println(map.remove(key));
        
                }
                //編譯後
                ArrayList<String> strings = new ArrayList(map.keySet());
                Iterator var3 = strings.iterator();
        
                while(var3.hasNext()) {
                    String key = (String)var3.next();
                    System.out.println((String)map.get(key));
                    System.out.println((String)map.remove(key));
                }
        • 或可使用ConcurrentHashMap解決併發修改異常:使用ConcurrentHashMap後上面的三種方式都不會出現併發異常問題。
          ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(2);
    2. ArrayList的遍歷中修改一樣出現ConcurrentModificationException併發修改異常:

      1. 解析:使用Iterator迭代器(加強for循環也是使用Iterator)在next進行判斷,而後使用ArrayList的add()、remove()進行修改操做
            public Iterator<E> iterator() {
                return new Itr();
            }
            private class Itr implements Iterator<E> {
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= size)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[lastRet = i];
                }
                final void checkForComodification() {
                    //判斷計數器和指望的計數器是否一致,因爲ArrayList的add()、remove()、trimToSize()都會對modCount+1,致使遍歷時修改會拋出異常
                    if (modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                }
            } 
      2. 解決方式:

        1. 直接使用普通for同時遍歷和修改:
              for(int i=0;i<list.size();i++){
                  String str = list.get(i);
                  if("str".equals(str)){
                      list.remove(str);
                      i= i-1;
                  }
              }
              public E get(int index) {
                  rangeCheck(index);//檢查索引範圍
                  return elementData(index);//直接從數組中獲取元素
              }
              private void rangeCheck(int index) {
                  if (index >= size)
                      throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
              }
              E elementData(int index) {
                  return (E) elementData[index];
              }     
        2. 使用ListIterator列表迭代器進行遍歷時添加使用ListIteratoradd()(只有添加操做),替換ArrayList的add():
              //====案例====
              ArrayList list = new ArrayList();
              list.add(1);
              ListIterator lit = list.listIterator();
              while (lit.hasNext()){
                  System.out.println(lit.next());
                  lit.add(2);
              }
              //====解析====
              public ListIterator<E> listIterator() {
                  return new ListItr(0);
              }
              private class ListItr extends Itr implements ListIterator<E> {
                  public void add(E e) {
                      checkForComodification();
          
                      try {
                          int i = cursor;
                          ArrayList.this.add(i, e);
                          cursor = i + 1;
                          lastRet = -1;
                          //將指望的計數器更新爲修改計數器值,這樣下次next判斷就不會出現問題
                          expectedModCount = modCount;
                      } catch (IndexOutOfBoundsException ex) {
                          throw new ConcurrentModificationException();
                      }
                  }
              }
        3. 使用Iterator迭代器進行遍歷時刪除使用Iteratorremove()(只有刪除操做),替換ArrayList的remove():
              //====案例====
              ArrayList list = new ArrayList();
              list.add(1);
              list.add(2);
              Iterator lit = list.iterator();
              while (lit.hasNext()){
                  Integer i = (Integer)lit.next();
                  if(1==i) {
                      lit.remove();
                  }
              }
              System.out.println(list);
              //====解析====
              public Iterator<E> iterator() {
                  return new Itr();
              }
              private class Itr implements Iterator<E> {
                  public void remove() {
                      if (lastRet < 0)
                          throw new IllegalStateException();
                      checkForComodification();
                      try {
                          //刪除當前遍歷到的元素
                          ArrayList.this.remove(lastRet);
                          cursor = lastRet;
                          lastRet = -1;
                          //將指望的計數器更新爲修改計數器值,這樣下次next判斷就不會出現問題
                          expectedModCount = modCount;
                      } catch (IndexOutOfBoundsException ex) {
                          throw new ConcurrentModificationException();
                      }
                  }
              }
相關文章
相關標籤/搜索