Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 775
Matt Thompson Avatar asked Jun 28 '12 14:06

Matt Thompson


2 Answers

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();
like image 75
Jesper Avatar answered Oct 20 '22 14:10

Jesper


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

like image 22
didxga Avatar answered Oct 20 '22 14:10

didxga