Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Iterator over Iterators

843793May 22 2010 — edited May 22 2010
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.

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Jun 19 2010
Added on May 22 2010
3 comments
191 views