This has nothing to do with generics, and everything to do with the fact that you're modifying a collection directly (in insert
) and then trying to use an iterator which was created before the insertion. Don't do it.
From the docs of ArrayList
:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
If you must keep the iterator around, use that to add a new value instead:
private ListIterator<T> itor; // Not just Iterator<T>; you need the add method
public void insert(T element)
{
itor.add(element);
}
It would be better not to keep the iterator around though - it's very rarely a good idea to use an iterator other than for a direct loop.