Search code examples
javagenericsiterator

Why is this an unchecked cast? And how to fix it?


I have the following code:

public final <T extends Component> T getComponent(Class<T> type) {
    Iterator<Component> it = components.iterator();

    while(it.hasNext()) {
        Component next = it.next();

        if(type.isAssignableFrom(next.getClass()))
            return (T)next; // Why is this an unchecked cast from Component to T?
    }

    return null;
}

And for some reason, return (T)next; is an unchecked cast from Component to T.

I'm not sure as to why this is, because T has to extend Component, it should be able to safely cast it to any subclasses of Component, right?

If I manually do return (TestComponent)next; and change the return type to TestComponent it works fine, so why doesn't it work with T?


Solution

  • Others have described the problem, here is the solution with cleaner test:

    if (type.isInstance(next)) {
        return type.cast(next);
    }