2

在我的哈希集代码中,我想实现一个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;
  }
4

1 回答 1

2

添加一个实例变量int modcount = 0;每次调用 mutator(例如addor remove)时递增它。当你创建一个新的迭代器时,设置它的实例变量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.

于 2013-04-29T04:37:23.637 回答