Attempting to generics-ify some legacy code, I'm stuck. I have a ParentObject which wraps a ChildObject to provide group-type operations on the ChildObject. Most usefully, it allows iteration over the collection of child objects. When I try to add some generics to the mix, I can't work out how to make it play friendly with the iterator method without either a "naming clash" error, or in the example below, a "The return type is incompatible with Iterable.iterator()" error. Any suggestions? (Bonus question - is there a better way to write the avoid thegetChildObjectByIndex() method to avoid type erasure complier warning other than suppressing the warnings?) Thanks a lot in advance for any help
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();
}
}
? superandT extendsabsolutely necessary? If not, just remove them. Else update your question to clarify the functional design requirement about those necessities more. Only then we can suggest the best suitable generifications.superdoesn't mean what you think it means.