gpt4 book ai didi

Java - 使用带有接口(interface)的哈希表作为值

转载 作者:行者123 更新时间:2023-12-02 08:22:07 25 4
gpt4 key购买 nike

我有一个接口(interface) IMyInterface。一组实现该接口(interface)的类:Class1、Class2...

现在我想创建一个哈希表来存储任何实现 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

关于Java - 使用带有接口(interface)的哈希表作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5282235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com