Hi,
I am trying to write an ItIterator class which would iterate over the elements of multiple iterator.
import java.util.ArrayList;
import java.util.Iterator;
public class ItIterator<T> implements Iterator<T> {
private Iterator<T> currIterator=null;
private ArrayList<Iterator<T>> arr;
private Iterator<Iterator<T>> arrIterator;
public ItIterator()
{
arr=new ArrayList<Iterator<T>>();
arrIterator=arr.iterator();
}
public void add(Iterator<T> e)
{
arr.add(e);
}
@Override
public boolean hasNext()
{
if(currIterator!=null && currIterator.hasNext())
return true;
while(arrIterator.hasNext())
{
currIterator=arrIterator.next();
if(currIterator.hasNext())
return true;
}
return false;
}
@Override
public T next()
{
if(currIterator!=null && currIterator.hasNext())
return currIterator.next();
while(arrIterator.hasNext())
{
currIterator=arrIterator.next();
if(currIterator.hasNext())
return currIterator.next();
}
return null;
}
@Override
public void remove()
{
if(currIterator!=null && currIterator.hasNext())
currIterator.remove();
while(arrIterator.hasNext())
{
currIterator=arrIterator.next();
if(currIterator.hasNext())
{
currIterator.remove();
return;
}
}
}
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class Test
{
public static void main(String args[])
{
ItIterator<Integer> i=new ItIterator<Integer>();
ArrayList<Integer> a=new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
ArrayList<Integer> b=new ArrayList<Integer>();
b.add(4);
b.add(5);
b.add(6);
i.add(a.iterator());
i.add(b.iterator());
while(i.hasNext())
System.out.println(i.next().toString());
}
}
Te above code complies without any error but gives a runtime exception as follows:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at ItIterator.hasNext(ItIterator.java:31)
at Test.main(Test.java:28)
If someone could help me out solving this exception that would be great.