简体   繁体   中英

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 ?

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> 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM