0

Hi I want to implement the iterator for a class that extends abstract Collection.

class Name<E extends Comparable<E>>
extends AbstractCollection<CompRational>
implements Iterable<E>{
...
  public Iterator<E> iterator(){
    return new NameIterator<E>(this);
  }
...
}

and the Iterator should look like this

class NameIterator<E extends Comparable<E>> implements Iterator<E>{
    private Name<E> tree;
    private int pos = 0;

    public NameIterator ( Name<E> t) {
        ...
    }

    @Override
    public boolean hasNext() {
        ...
    }

    @Override
    public E next () {
        ...
    }

    @Override
    public void remove(){
        throw new UnsupportedOperationException();
    }   
}

The error message that I receive is that my class Name does not override or implement Iterator and the iterator cannot override iterator because the types are incompatible and it says that I'm using two different but where and how and how can i get rid of it?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
haxor789
  • 604
  • 6
  • 18
  • Actually what are you trying to do implementing 2 `Iterators`? why do you want to have both class implement `Iterator`? – Blip Jun 05 '15 at 11:47
  • You probably want to implement Iterable in the first one. Not Iterator. – Nytux Jun 05 '15 at 11:52
  • Yes, sry the public class should be iterable not Iterator. But I did this in the actual code. – haxor789 Jun 05 '15 at 12:40
  • [The answer to your question is here](http://stackoverflow.com/q/2685537/521799). The other question uses `Comparable` as a common super interface, rather than `Iterable`, but the problem is the same – Lukas Eder Jun 05 '15 at 12:52
  • Thank you, but I don't think this is was the problem. I just used an existing type where I indented to use another generic E. Sry for the confusion didn't realized this bug when writing the question. – haxor789 Jun 05 '15 at 12:57
  • @haxor789: It's not exactly the same problem, true. Yet your answer is still in that other question :) – Lukas Eder Jun 05 '15 at 12:58

1 Answers1

2

Don't have the Collection implement Iterator. That's for the Iterator instance. Your concrete collection needs to extend AbstractCollection, and your NameIterator implements Iterator.

class Name<E extends Comparable<E>> extends AbstractCollection {

    @Override
    public NameIterator<E> iterator() {
        return new NameIterator<>();
    }

    @Override
    public int size() {
        return 0;
    }
}

class NameIterator<E extends Comparable<E>> implements Iterator{

    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    public E next() {
        return null;
    }
}
MadConan
  • 3,749
  • 1
  • 16
  • 27