I extended a TreeSet with an index so that all the add/remove operations needed to be overridden in order to keep the index up to date (omitted for brevity from the code below). The default iterator allows removing of elements, however, which circumvents this and thus needs to be made read only. However, when I create an unmodifiable view on the set, it calls the iterator causing an infinite loop. I unsuccessfully tried using casts and super. How can create this read only iterator without an infinite loop?
import java.util.Collections;
import java.util.Iterator;
import java.util.TreeSet;
public class MySet<T> extends TreeSet<T>
{
// StackOverflowError
@Override public Iterator<T> iterator()
{return Collections.unmodifiableSortedSet(this).iterator();}
// Compile Error
// @Override public Iterator<T> iterator()
// {return Collections.unmodifiableSortedSet(super).iterator();}
public static void main(String[] args)
{new MySet().iterator();}
}