In a class, I have a container:
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!
}
}
The interface:
public interface MyClassInterface {
//Is
public Iterator iterator();
//Should be
public Iterator<OtherClassInterface>();
}
Then again, OtherClass also has an interface OtherClassInterface.
I want only the interfaces to be used by whom who works with the code.
The problem is that I want to use the full OtherClass inside MyClass but pass an iterator over LinkedList<OtherClassInterface> to the caller of MyClassInterface.iterator().
I could not cast the existing LinkedList<OtherClass> to LinkedList<OtherClassInterface> inside MyClass to return the desired iterator.
How to handle such a situation?
EDIT
Reason why I want this behaviour
For another developer, I want to provide two interfaces: The first gives him access to a higher data structure which contains a lower data structure which he should access by the second interface. In the implementing class of the higher interface I use the type of the lower data structure directly, not over the lower interface.
As mentioned, the other developer wants to use both interfaces. Over the higher one I want to provide an iterator that gives access to elements of the lower interface – but not to the class that implements the interface.
Additional needs
I also want the returned iterator to be “Iterable” i.e. so that I can use the “for each” construct. Is this also possible with *waxwing*s solution? If possible, I wouldn´t like to implement an own iterator – for me this seems not neccessary because I just want to give an iterator over elements of the interface instead of the implementing class.
The interface can be defined like this:
Then the implementation should look like this:
This has the following advantages:
list()by anOtherClassobject you will get aLinkedList<OtherClass>list()by anOtherClassInterfaceobject you will get aLinkedList<OtherClassInterface>list().iterator()