迭代结束时HashSet的条目给出ConcurrentModificationException

Sar*_*abo 1 java generics collections multithreading exception

我在测试使用hashset的类时遇到问题,当我遍历元素时,我得到了一个ConcurrentModificationException尽管,据我所知(单线程应用程序),只有一个线程访问过类随时.当两个相同的条目添加到列表时,这会中断.

private final HashSet<?> entries = new HashSet<>(10);
/**
 * Updates an existing entry if it exists, if not, adds it to the library.
 *
 * @param <T> The type to add
 * @param object The object to test for existence of and to update to
 * @param key The class of the object
 */
public <T> void add(T object, Class<T> key) {
    this.entries.stream().filter((entry) -> (object.equals(entry.getStorage()))).forEach(this.entries::remove);
    this.entries.add(new ClanLibraryEntry<>(object, key));
}
Run Code Online (Sandbox Code Playgroud)

Bre*_*ken 5

注意HashSet的javadoc :

这个类的迭代器方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候修改了set,​​除了通过迭代器自己的remove方法之外,Iterator抛出ConcurrentModificationException.

这实际上不需要多个线程.它只需要通过其他东西修改集合Iterator.