Java wrap a properly typed list of subtypes

If you want to create a List or Collection in Java that uses a subclass of a type YourType and it is safe to cast, you can use the following snippet to wrap the objects into the right list:

@SuppressWarnings( "unchecked" )
protected <T> List<T> wrapList( Collection<? extends YourObject> collection )
{
    List<T> result = Lists.newArrayList();
    for ( YourObject state : collection )
    {
        result.add( (T) state );
    }
    return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *