【发布时间】:2013-11-13 05:44:50
【问题描述】:
我有一个 LinkedHashSet 的 ThisType 值。 ThisType 正在实现接口 ThatType。
我需要这个集合的多态使用——能够将它指向为 LinkedHashSet。
这是怎么做到的?
我知道这是一个幼稚的问题,但我尝试过的几件事没有奏效,我想以正确的方式去做。
提前致谢。
//================================
更新:更多细节:
在下面的代码中,ThisType 实现了 ThatType-- ThatType 是一个接口。
//LinkedHashMap<Integer, ? extends ThatType> theMap = new LinkedHashMap<>();
LinkedHashMap<Integer, ThisType> theMap = new LinkedHashMap<>();
for (Integer key:intArray) {
ThisType a = new ThisType();
if (theMap.containsKey(key)) {
a = theMap.get(key);
a.doStuff();
} else {
a.doOtherStuff();
}
theMap.put(key, a);
}
最后,我想将 theMap 作为 ThatType ** 的集合返回,而不是 **ThisType。
这就是链条断裂的地方。使用注释行(第一行)进行声明会导致散列的 put() 和 get() 方法出现类型不匹配错误。
不确定这是否重要——但是, 我将结果返回为 LinkedHashSet。我正在进行从 LinkedHashMap 到 LinkedHashSet 的转换。但是,对于映射或集合中的集合值的多态引用,没有任何效果。到目前为止,我在所有这些操作中使用的所有且唯一的类型是 ThisType。 ThatType 几乎在我尝试过的任何地方都给了我一些错误。
【问题讨论】:
-
你到底需要做什么?
-
我会把它作为参数传递
-
我读了三次,仍然无法理解您想要达到的目标。
-
你能详细说明“多态使用”吗?
-
或者更确切地说,将它作为 LinkedHashSet
返回,而里面到处都是 LinkedHashSet 。
标签: java collections polymorphism