This is probably a simple misunderstanding on my part.
Have a simple interface:
public interface IParams extends Map<String,String> {
}
Then I try to use:
IParams params = (IParams) new HashMap<String,String>();
Passes syntax and compile but at runtime i get:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.foobar.IParams
Any insight into where my misunderstanding of generics is in this case?
HashMapdoes not implement your interfaceIParams, so you cannot cast aHashMapto anIParams. This doesn’t have anything to do with generics.IParamsandHashMapare “siblings”, in the sense that both implement or extendMap. But that doesn’t mean you can treat aHashMapas if it is anIParams. Suppose that you would add a method to yourIParamsinterface.Ofcourse,
someMethoddoesn’t exist inHashMap. If casting aHashMaptoIParamswould work, what would you expect to happen if you’d attempt to call the method?With regard to your comment:
What you could do is create a class that implements
IParamsand extendsHashMap: