Help me understand these generic method warnings

Posted by Raj on Stack Overflow See other posts from Stack Overflow or by Raj
Published on 2010-12-23T01:27:48Z Indexed on 2010/12/23 1:53 UTC
Read the original article Hit count: 644

Filed under:
|

Folks, I have a base class, say:

public class BaseType { private String id; ... }

and then three subclasses:

public class TypeA extends BaseType { ... }
public class TypeB extends BaseType { ... }
public class TypeC extends BaseType { ... }

I have a container class that maintains lists of objects of these types:

public class Container
{
    private List<TypeA> aList;
    private List<TypeB> bList;
    private List<TypeC> cList;

    // finder method goes here
}

And now I want to add a finder method to container that will find an object from one of the lists. The finder method is written as follows:

public <T extends BaseType> T find( String id, Class<T> clazz )
{
    final List<T> collection;
    if( clazz == TypeA.class )
    {
        collection = (List<T>)aList;
    }
    else if( clazz == TypeB.class )
    {
        collection = (List<T>)bList;
    }
    else if( clazz == TypeC.class )
    {
        collection = (List<T>)cList;
    }
    else return null;

    for( final BaseType value : collection )
    {
        if( value.getId().equals( id ) )
        {
            return (T)value;
        }
    }

    return null;

}

My question is this: If I don't add all the casts to T in my finder above, I get compile errors. I think the compile should be able to infer the types based on parametrization of the generic method (). Can anyone explain this?

Thanks.

-Raj

© Stack Overflow or respective owner

Related posts about java

Related posts about generics