尝试使用泛型 - 如果遗留一些遗留代码,我就会陷入困境。我有一个ParentObject,它包装一个ChildObject以在ChildObject上提供组类型操作。最有用的是,它允许迭代子对象的集合。 当我尝试在混合中添加一些泛型时,我无法弄清楚如何在没有“命名冲突”错误的情况下使用迭代器方法使其友好,或者在下面的示例中,“返回类型与以下内容不兼容Iterable.iterator()“错误。 有什么建议? (额外的问题 - 是否有更好的方法来编写避免thegetChildObjectByIndex()方法以避免类型擦除编译器警告而不是抑制警告?) 非常感谢您提供任何帮助
public class ParentObject implements Iterable<ChildObject> {
protected List<? super ChildObject> theChildObjects;
@SuppressWarnings("unchecked")
public <T extends ChildObject> T getChildObjectByIndex(int idx) {
return (T)theChildObjects.get(idx);
}
public Iterator<? super ChildObject> iterator() {
return java.util.Collections.unmodifiableCollection(this.theChildObjects).iterator();
}
}
答案 0 :(得分:3)
如果ParentObject只包含一个ChildObject子类型,则可以对该类型的ParentObject进行参数化:
public class ParentObject<T extends ChildObject> implements Iterable<T> {
protected List<T> theChildObjects;
public T getChildObjectByIndex(int idx) {
return theChildObjects.get(idx);
}
public Iterator<T> iterator() {
return java.util.Collections.unmodifiableCollection(this.theChildObjects).iterator();
}
}
答案 1 :(得分:0)
似乎在您的示例中,ParentObject是某种与ChildObject没有任何关系的容器类。 ChildObject是否扩展ParentObject?如果是这样,那似乎不太理想。看起来你应该在泛型中使用“extends”而不是super,除非我只是误解了你想要做的事情。以下怎么样?或者这对你想做的事情来说太简单了?
public class WidgetContainer<T> implements Iterable<T> {
protected List<T> theWidgets;
public T getWidgetByIndex(int idx) {
return theWidgets.get(idx);
}
public Iterator<T> iterator() {
return Collections.unmodifiableCollection(theWidgets).iterator();
}
}
WidgetContainer<SomeWidget> myWidgetContainer = new WidgetContainer<SomeWidget>();
此外,我可能会缓存不可修改集合的副本,并在每次需要迭代器时使用它,而不是在运行时构建它。