【发布时间】:2012-05-24 23:56:20
【问题描述】:
在一个类中,我有一个容器:
public class MyClass implements MyClassInterface {
private LinkedList<OtherClass> list; //Need to use 'OtherClass' instead of 'OtherClassInterface here
@Override
public Iterator iterator() {
return list.iterator; //Problem!
}
}
界面:
public interface MyClassInterface {
//Is
public Iterator iterator();
//Should be
public Iterator<OtherClassInterface>();
}
再一次,OtherClass 也有一个接口OtherClassInterface。
我只希望使用代码的人使用接口。
问题是我想在MyClass 中使用完整的OtherClass,但将LinkedList<OtherClassInterface> 上的迭代器传递给MyClassInterface.iterator() 的调用者。
我无法将现有的 LinkedList<OtherClass> 转换为 LinkedList<OtherClassInterface> 内的 MyClass 以返回所需的迭代器。
遇到这种情况该如何处理?
编辑
我想要这种行为的原因
对于另一个开发人员,我想提供两个接口:第一个让他可以访问更高的数据结构,其中包含他应该通过第二个接口访问的更低的数据结构。在上层接口的实现类中,我直接使用下层数据结构的类型,而不是通过下层接口。
如前所述,其他开发人员希望同时使用这两个接口。在较高的接口上,我想提供一个迭代器,它可以访问较低接口的元素,但不能访问实现该接口的类。
其他需求
我还希望返回的迭代器是“Iterable”,即我可以使用“for each”构造。 *waxwing*s 解决方案也可以做到这一点吗?如果可能的话,我不想实现自己的迭代器 - 对我来说这似乎没有必要,因为我只想为接口的元素而不是实现类提供迭代器。
【问题讨论】:
-
更好的是为什么不解释你真正想要实现的目标?可能有其他/更好的方法?毕竟你遇到的这个问题可能有更多的解决方案
标签: java interface iterator type-conversion