Stephan
Stephan

Reputation: 43083

Java - Using Hashtable with Interface as value

I have one interface IMyInterface. A set of classes that implements this interface : Class1, Class2...

Now i want to create a Hashtable that stores any class implementing IMyInterface.

Hashtable<String,? extends IMyInterface> ht = new Hashtable<String,? extends IMyInterface>();
ht.add("foo",new Class1());

The compiler complains that it cannot instiate ht and that it cannot add Class1 because the add method is not defined to do so. add method expects IMyInterface :\

How can i do ?

Upvotes: 0

Views: 2119

Answers (2)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

The type you have written, Hashtable<String,? extends IMyInterface> means a Hashtable which stores as values elements of some subtype of IMyInterface, but we don't know which one. This is acceptable for a variable type (and then you can't add any keys to it, since the compiler can't be sure you are using the right subtype), but it is not usable for a constructor invocation.

What you want is a Hashtable<String, IMyInterface>, which means any object implementing IMyInterface can be a value.

By the way, better use Map<String, IMyInterface> for the variable and HashMap<String, IMyInterface> for the constructor instead of Hashtable.

Upvotes: 0

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49237

Simply use:

Hashtable<String, IMyInterface> table = new Hashtable<String, IMyInterface>();
table.put("foo", new Class1());

Given that Class1 implements IMyInterface.

Upvotes: 2

Related Questions