Implementing an iterator with bounded parameter type
I'd like to implement my own iterator for subclasses of (let's say) Element using generics. I have a class that wraps a Set<Element> and I want to create a method that takes a Class object as argument and returns an Iterator with the same parameter type as the argument (a kind of filter...):
public <Textends Element> Iterator<T> iterator(Class<T> c){
returnnew IteratorImpl<T>(c);
}
My question is: Is it possible to do so? If yes, what do I have to change in the following code (especially in the next() method) to make it work? The problem is that I can't change the returned type in the method signature, and that the field "current" is not recognized as the type of T. I'm also pretty sure that casting current to T is considered bad practice and so I want to avoid it.
public IteratorImpl<Textends Element>implements Iterator<T>{
private Element current =null;
private Class<T> c =null;
public IteratorImpl(Class<T> c){
this.c = c;
}
publicboolean hasNext(){
// some code that sets the current element...
}
public T next(){
return (T)current;// bad practice?
}
publicvoid remove(){
// some code...
}
}
Any idea?

