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?

[2323 byte] By [jeromeda] at [2007-10-3 4:40:12]
# 1

Your code compiles more-or-less as-is:class IteratorTest<Element> {

public <T extends Element> Iterator<T> iterator(Class<T> c) {

return new IteratorImpl<T>(c);

}

class IteratorImpl<T extends Element> implements Iterator<T> {

private Element current = null;

private Class<T> c = null;

public IteratorImpl(Class<T> c) {

this.c = c;

}

public boolean hasNext() {

throw new RuntimeException("Implement me");

}

public T next() {

if (hasNext())

return (T)current; // bad practice

else

throw new NoSuchElementException();

}

public void remove() {

throw new RuntimeException("Implement me");

}

}

}

You get one warning from the line you identify as "bad practice," but this goes away if you just change it toreturn c.cast(current);

jpmrsta at 2007-7-14 22:44:09 > top of Java-index,Core,Core APIs...
# 2
Thank you for the answer... The code now compiles with no warnings.
jeromeda at 2007-7-14 22:44:09 > top of Java-index,Core,Core APIs...