Reputation: 4872
I have been lost for the last two days in the whole implementing the Iterable interface thing.
I have read some blogs and such and have figured out that to implement Iterable I obviously need a function which returns Iterator called iterator() but have gotten lost in the whole implementation process.
Now, what I have read is that I need
public class MyCollection<E> implements Iterable<E>{
public Iterator<E> iterator() {
return new MyIterator<E>();
}
}
and then I need the
public class MyIterator <T> implements Iterator<T> {
public boolean hasNext() {
//implement...
}
public T next() {
//implement...;
}
public void remove() {
//implement... if supported.
}
}
Now, what I do not understand is what types do the E and T need to be. Which has to be something related to what I'm iterating over and which can/has to be generic?
I have tried doing
public Iterator<SimpleHashtable.TableEntry> iterator() {
return new TableEntryIterator<SimpleHashtable.TableEntry>();
}
But I get the Type mismatch: cannot convert from SimpleHashtable.TableEntryIterator<SimpleHashtable.TableEntry> to Iterator<SimpleHashtable.TableEntry>
error.
Plox help guize
Upvotes: 1
Views: 41
Reputation: 77187
E
and T
are generic type parameters, and if your implementation is generic, then leave them as parameters. (It's also possible to write a class that fixes one or more of the parameters, such as MyIntegerCollection implements Iterator<Integer>
.)
In this case, the E
stands for "element" (the type of the elements in the collection), and T
stands for "type" (the type of object returned by the iterator). There's no inherent requirement for how to name these, but those are the conventions for collections and iterators.
Your approach is generally correct. Note, however, that if the Iterator
is an inner class of the collection, which is common, you should not introduce a new generic parameter; just use the same E
from the collection declaration.
As to the specific error you're getting, we'll need to see that code. Most likely, you forgot to declare TableEntryIterator implements Iterator<E>
.
Upvotes: 3