Given this code:
public final class MyMap extends HashMap<MyClass<? extends MyInterface>, MyInterface>
{
public <T extends MyInterface> T put(MyClass<T> key, T value)
{
return (T)key.getClass().getComponentType().cast(super.put(key, value));
}
}
I get an unchecked cast warning on the cast from MyInterface to T.
I really dont like it so I use the Class.cast() method to cast it instead. Now my new function looks like this:
public final class MyMap extends HashMap<MyClass<? extends MyInterface>, MyInterface>
{
public <T extends MyInterface> T put(MyClass<T> key, T value)
{
Class<T> cl = (Class<T>)key.getClass().getComponentType();
return cl.cast(super.put(key, value));
}
}
But this one gives an unchecked cast warning from Class<?> to Class<T> as Object.getClass() returns a wildcard class.
However, is there any chance that key.getClass().getComponentType() will not return Class<T> as T is defined by the component type of the class of key?