Unable to cast a HashMap<String,String> to a Interface extending Map<String,String>
Asked Answered
S

2

5

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?

Stewartstewed answered 28/6, 2012 at 14:22 Comment(3)
You are not misunderstanding generics, you are misunderstanding inheritance.Goudy
Any reason to extend Map? Are you overriding any methods?Videogenic
The intention is to create an interface which hides the generics, and also to hold (not shown in the example) map key string definitionsStewartstewed
M
11

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();
Muckrake answered 28/6, 2012 at 14:25 Comment(1)
Fantastic explanation, I wasn't thinking in terms of siblings. I was trying too hard to use the HashMap implementation directly and your suggestion of creating a quick concrete class looks pretty reasonable. Thanks Jesper.Stewartstewed
H
3

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

Hidebound answered 28/6, 2012 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.