I'm having the following issue:
Given:
public class A{
Collection<B> elements = new ArrayList<B>();
}
public class B{
Collection<B> linkedElements = new ArrayList<B>();
}
All the elements of linkedElements belongs to elements too. I want that each time that an element is deleted from the elements collection, its linked elements gets deleted from that collection too. I've tried attaching a observer to the Iterator.remove operation and fire there the removal of linkedElements from the elements list, but because of the logic itself, I always run into a ConcurrentModificationException.
Update: This is the code that causes the error:
public class A{
Collection<B> elements = new ArrayList<B>(){
public Iterator<B> iterator() {
return new ProxyIterator(super.iterator());
};
private class ProxyIterator implements Iterator{
Iterator it;
Object lastObject;
public ProxyIterator(Iterator proxied){
it = proxied;
}
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public Object next() {
return lastObject = it.next();
}
@Override
public void remove() {
it.remove()
for (B linkedElement : ((B)lastObject).getlinkedElements()) {
A.this.getElements().remove(linkedElement);
}
}
}
}
With this code, just calling a A.getElements().clear()
will fire a ConcurrentModificationException
... and its ok, because I'm removing all linked elements from from the elements list while removing one single element. That's why I need another approach.