HashMap不实现您的接口IParams,因此您无法将HashMap强制转换为IParams.这与泛型没有任何关系.
从实现或扩展Map的角度来看,IParams和HashMap都是“兄弟姐妹”.但这并不意味着您可以将HashMap视为IParams.假设您要向IParams接口添加方法.
public interface IParams extends Map {
void someMethod();
}
当然,HashMap中不存在someMethod.如果将HashMap转换为IParams会起作用,如果你试图调用该方法,你会发生什么?
IParams params = (IParams) new HashMap();
// What's supposed to happen here? HashMap doesn't have someMethod.
params.someMethod();
关于你的评论:
The intention is to create an interface which hides the generics, and also to hold (not shown in the example) map key string definitions
你可以做的是创建一个实现IParams并扩展HashMap的类:
public class Params extends HashMap implements IParams {
// ...
}
IParams params = new Params();