I'm implementing a custom doubly linked list in Java and I don't know exactly how to implement an iterator for it so that it can for example be easily iterated using a foreach (enhanced for) loop.
I basically want to be able to get the next or previous element with something like the code below, where it starts from a given Node and then continues to get the "next" (or "previous") element in the node variable. I want it to stop once "next" is null (which obviously will be handled by "hasNext"). I know that the approach below might not strictly make sense from a Java perspective because what I'm searching for is a for loop that does not loop through a Collection but logically it makes sense.
for (Node node : firstNode)
Otherwise I would need to do something like
Node node = getFirstNode();
while (node != null) {
//do stuff with current node
node = node.next;
}
The reason I don't want to use java.util.LinkedList is because of the lower amount of memory that will be used with the custom approach. Basically I also need the "next" and "previous" references in a Node so that I can easily access them with just having the Node at hand. If I would go with the java.util.LinkedList approach for each Node additionally I would need to keep an integer index to indicate at which index the object is located in the list and then be able to access "next" or "previous" or edit the list at that location in O(1) time.
Note that I would still prefer the java.util.LinkedList approach If there is a way to get away without needing the indexInList variable in the Node itself
indexInListvariable for?