开发者

Java - Using Hashtable with Interface as value

开发者 https://www.devze.com 2023-02-16 15:18 出处:网络
I have one interface IMyInterface. A set of classes that implements this interface : Class1, Class2...开发者_运维技巧

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 ?


Simply use:

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

Given that Class1 implements IMyInterface.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消