在我的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;
}
答案 0 :(得分:2)
添加实例变量int modcount = 0
;每次调用mutator(例如add
或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()
则不会。{/ p>
如果您的迭代器实现了remove
或任何其他mutator,那么这些增量myModcount
以及modcount
。