这可能是我的一个简单的误解。
有一个简单的界面:
public interface IParams extends Map<String,String> {
}
然后我尝试使用:
IParams params = (IParams) new HashMap<String,String>();
通过语法并编译但在运行时我得到:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.foobar.IParams
在这种情况下,我对泛型的误解在哪里?
最佳答案
HashMap
没有实现您的接口(interface) IParams
,因此您不能将 HashMap
转换为 IParams
。这与泛型没有任何关系。
IParams
和 HashMap
是“ sibling ”,因为它们都实现或扩展了 Map
。但这并不意味着您可以将 HashMap
视为 IParams
。假设您要向 IParams
接口(interface)添加一个方法。
public interface IParams extends Map<String, String> {
void someMethod();
}
当然,someMethod
在HashMap
中是不存在的。如果将 HashMap
转换为 IParams
可行,如果您尝试调用该方法,您期望发生什么?
IParams params = (IParams) new HashMap<String,String>();
// 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<String, String> implements IParams {
// ...
}
IParams params = new Params();
关于java - 无法将 HashMap<String,String> 转换为扩展 Map<String,String> 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246771/