I think I have used try/catch for every place where an index out of bounds exception might occur. Not sure what else to do.
package com.codegym.task.task37.task3701;
import java.util.*;
/*
Circular iterator
*/
public class Solution<T> extends ArrayList<T>
{
public static void main(String[] args)
{
Solution<Integer> list = new Solution<>();
list.add(1);
list.add(2);
list.add(3);
int count = 0;
for (Integer i : list)
{
//1 2 3 1 2 3 1 2 3 1
System.out.print(i + " ");
count++;
if (count == 10)
{
break;
}
}
}
@Override
public Iterator<T> iterator()
{
return new CircularIterator();
}
public class CircularIterator implements Iterator<T>
{
int nextIndex = 0;
int removalIndex = 0;
@Override
public boolean hasNext()
{
return size() > 0;
}
@Override
public T next()
{
if(nextIndex >= size())
{
nextIndex = 0;
}
removalIndex = nextIndex;
try
{
return (T) Solution.this.toArray()[nextIndex++];
}
catch(Exception e)
{
throw new ConcurrentModificationException();
}
}
@Override
public void remove()
{
try
{
Solution.this.remove(removalIndex);
}
catch(Exception e)
{
throw new ConcurrentModificationException();
}
}
}
}