在HashSt代码中实现throw ConcurrentModificationException

时间:2013-04-29 04:22:46

标签: java

在我的hashset代码中 我想实现一个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;
  }

1 个答案:

答案 0 :(得分:2)

添加实例变量int modcount = 0;每次调用mutator(例如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()则不会。{/ p>

如果您的迭代器实现了remove或任何其他mutator,那么这些增量myModcount以及modcount