Cannot pass HashMap <String, String> to an interface extending Map <String, String>

This is probably a simple misunderstanding on my part.

Simple interface:

public interface IParams extends Map<String,String> {
}

Then I try to use:

IParams params = (IParams) new HashMap<String,String>();

Skips syntax and compilation, 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?

+5
source share
2 answers

HashMapdoes not implement your interface IParams, so you cannot use HashMapfor IParams. This has nothing to do with generics.

IParams HashMap " " , Map. , HashMap, IParams. , IParams .

public interface IParams extends Map<String, String> {
    void someMethod();
}

, someMethod HashMap. HashMap IParams, , ?

IParams params = (IParams) new HashMap<String,String>();

// What supposed to happen here? HashMap doesn't have someMethod.
params.someMethod();

:

, , , ( )

, , IParams HashMap:

public class Params extends HashMap<String, String> implements IParams {
    // ...
}

IParams params = new Params();
+10

HashMap Map, IParams, Map, IParams, IParams

+3

All Articles