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?
HashMap
does not implement your interface IParams
, so you cannot cast a HashMap
to an IParams
. This doesn't have anything to do with generics.
IParams
and HashMap
are "siblings", in the sense that both implement or extend Map
. But that doesn't mean you can treat a HashMap
as if it is an IParams
. Suppose that you would add a method to your IParams
interface.
public interface IParams extends Map<String, String> {
void someMethod();
}
Ofcourse, someMethod
doesn't exist in HashMap
. If casting a HashMap
to IParams
would work, what would you expect to happen if you'd attempt to call the method?
IParams params = (IParams) new HashMap<String,String>();
// What's supposed to happen here? HashMap doesn't have someMethod.
params.someMethod();
With regard to your comment:
The intention is to create an interface which hides the generics, and also to hold (not shown in the example) map key string definitions
What you could do is create a class that implements IParams
and extends HashMap
:
public class Params extends HashMap<String, String> implements IParams {
// ...
}
IParams params = new Params();
HashMap
implemented Map
interface but not implemented your Interface IParams
even though you interface derived from Map
, you can not cast it to IParams
as it is not a type of IParams
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With