[英]Java - Using Hashtable with Interface as value
我有一个接口IMyInterface。 一组实现此接口的类:Class1,Class2 ......
现在我想创建一个Hashtable来存储任何实现IMyInterface的类。
Hashtable<String,? extends IMyInterface> ht = new Hashtable<String,? extends IMyInterface>();
ht.add("foo",new Class1());
编译器抱怨它无法填充ht并且它无法添加Class1,因为没有定义add方法这样做。 添加方法期望IMyInterface:\\
我能怎么做 ?
只需使用:
Hashtable<String, IMyInterface> table = new Hashtable<String, IMyInterface>();
table.put("foo", new Class1());
鉴于Class1
实现了IMyInterface
。
你写的类型, Hashtable<String,? extends IMyInterface>
Hashtable<String,? extends IMyInterface>
表示一个Hashtable,它存储IMyInterface
某些子类型的值元素,但我们不知道哪一个 。 这对于变量类型是可以接受的(然后你不能向它添加任何键,因为编译器不能确定你使用的是正确的子类型),但它不能用于构造函数调用。
你想要的是一个Hashtable<String, IMyInterface>
,这意味着任何实现IMyInterface的对象都可以是一个值。
顺便说一句,最好使用Map<String, IMyInterface>
作为变量,使用HashMap<String, IMyInterface>
作为构造函数而不是Hashtable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.