2013-04-29 19 views
2

在我的哈希集代碼 中,我想實現ConcurrentModificationException,以便當任何人試圖在迭代器之後添加或刪除時,它將被拋出。在HashSt代碼中執行throw ConcurrentModificationException

下面是代碼的一部分:

  /** Need to add ConcurrentModificationException stuff*/ 
    public boolean hasNext() 
    { 
    if (current != null && current.next != null) 
    { 
     return true; 
    } 
    for (int b = bucketIndex + 1; b < buckets.length; b++) 
    { 
     if (buckets[b] != null) 
     { 
      return true; 
     } 
    } 
    return false; 
    } 

    /** Need to add ConcurrentModificationException stuff*/ 
    public Object next() 
    { 
    if (current != null && current.next != null) 
    { 
     current = current.next; // Move to next element in bucket 
    } else 
    // Move to next bucket 
    { 
     do 
     { 
      bucketIndex++; 
      if (bucketIndex == buckets.length) 
      { 
       throw new NoSuchElementException(); 
      } 
      current = buckets[bucketIndex]; 
     } while (current == null); 
    } 
    return current.data; 
    } 
+0

你看看'AbstractList $ Itr'中的next()方法嗎? – prasanth 2013-04-29 04:38:25

回答

2

添加一個實例變量int modcount = 0;每增加一個增變器(例如addremove),就增加它。當你創建一個新的迭代器時,設置它的實例變量int myModcount = modcount;在其next方法中,如果myModtcount != modcount則拋出ConcurrentModificationException。 (我不認爲Java迭代器在hasNext方法拋出此,只有在next方法。)

的理由是,這可以讓你有多個迭代器,例如,

Iterator itr1 = hashMap.iterator(); 
hamMap.put(obj1, obj2); 
Iterator itr2 = hashMap.iterator(); 

在這點itr1.next()會拋出ConcurrentModificationException,但itr2.next()不會。

如果您的迭代器實現了remove或任何其他的增變器,那麼這些增量爲myModcount以及modcount

+0

我按照你所說的嘗試過,但我仍然通過了第一個測試用例,但最後2例並沒有給我例外哈哈。 – Kaaa 2013-04-29 04:49:37

+0

啊,我明白了。 :O 我試着實現 ,因爲我的測試人員專門爲它設置了一個try and catch塊。 – Kaaa 2013-04-29 04:52:19