Implementing an interface in an anonymous class as an iterator: type issue
<p>I'm having an issue with a project I'm working on. One of the things that needs to happen is to create an inspector which returns an iterator which implements an interface, while using an anonymous class. The context is a filesystem and basically, the iterator just needs to return the content of the directory the iterator works on. So here's the code I got at the moment:</p>

<p>Directory class:</p>

<pre><code>public class Directory {

   ...

    public Iterator&lt;DiskItem&gt; iterator() {
       return new DirectoryIterator() {

            int cursor = 1;
            int end = Directory.this.getNbItems();

            public boolean hasNext() {
                return this.cursor &lt; end;
            }

            public DiskItem next(){
                if(this.hasNext()) {
                    Directory.this.getItemAt(this.cursor++);
                }
                else
                    throw new NoSuchElementException();
            }

            @Override
            public int getNbRemainingItems() {
                return this.end - this.cursor;
            }

            @Override
            public DiskItem getCurrentItem() throws IndexOutOfBoundsException {
                return Directory.this.getItemAt(this.cursor);
            }

            @Override
            public void advance() {
                if(this.hasNext()) {
                    this.cursor++;
                }
                else
                    throw new NoSuchElementException();                 
            }

            @Override
            public void reset() {
                this.cursor = 1;            
            }
        }
}
</code></pre>

<p>DirectoryIterator Interface:</p>

<pre><code>public interface DirectoryIterator {

    int getNbRemainingItems();

    DiskItem getCurrentItem() throws IndexOutOfBoundsException;

    void advance();

    void reset();


}
</code></pre>

<p>The problem I'm having is getting the error</p>

<pre><code>Type mismatch: cannot convert from new DirectoryIterator(){} to Iterator&lt;DiskItem&gt;
</code></pre>

<p>and that's probably because DirectoryIterator doesn't have the type Iterator, but because it's an interface, I cannot give it any type. </p>

<p>Anyone an idea on how to solve this?</p>

<p>Thanks in advance</p>