0

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();}

}
Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118

1 Answers1

1

As assylias points out, you may want to go for composition instead of inheritance in this case.

If you really want to stick with inheritance, this may be sufficient:

@Override
public Iterator<T> iterator() {
    Iterator<T> delegate = super.iterator();
    return new Iterator<T>() {
        @Override
        public boolean hasNext() {
            return delegate.hasNext();
        }

        @Override
        public T next() {
            return delegate.next();
        }

    };
}

(Note, this is Java 8 which has a default implementation for remove. You'll have to override that method as well if you're on Java 7 or older.)

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • This resolved the issue, thank you very much (had to make `delegate` final though)! I agree that composition would be easier to implement but I already did all the work, in the next similar situation I will definitely use composition. – Konrad Höffner Sep 25 '14 at 09:09
  • Ringt. The "effectively final" is another Java 8 feature :-) – aioobe Sep 25 '14 at 09:21