Implementing Iterator for abstractCollection

1k views Asked by At

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?

1

There are 1 answers

0
MadConan On BEST ANSWER

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