I never understood this: why is it that I can't seem to find a core collections api somewhere that Allows me to retrieve elements that have a direct .next() or .previous() method on them without all the boilerplate or having to implement my own version of a LinkdList. The benefit? I can iterate directly over my returned elements without the need of an iterator, which seems to me one possible main motivator of having a LinkedList in the first place.
class Link { ... }
LinkedList<Link> linksByPosition = ...
Map<String,Link> linksByName = ...
Link linkWithName = linksByName.get("name");
Link nextLink = ??? // Do you get how complex it is?
Do you get how complex the ???
might be? I need to consider a scan through every element to find the matching one first to know at what position it is, before I can get the next one ...
Now consider this altered form, with a SmarterLinkedList
that returns me implements of a predefined LinkdListNode
.
class Link extends AbstractLinkedListNode<Link> { ... }
SmarterLinkedList<Link> linksByPosition = ...
Map<String,Link> linksByName = ...
Link linkWithName = linksByName.get("name");
Link nextLink = linkWithName.next();
If internally, it is already tracking the linking, why would you not want to expose that part of the API to the developer? It seems to me endlessly useful?
Now lets say, I will make the requirements a little complexer, now I also want to append an item right after the one I am holding. In the first version of the code, while searching for the matching Link
, I can also maintain an index so I know at which point to insert. This way I can call the LinkedList.add(index+1,newLink)
method. You know what this is doing behind the scenes right? Yes, internally, it again iterates to the right position index+1
times until it reaches the right position for the insertion.
However if the LinkedListNode
also requires me to expose methods for insertAfter
, insertBefore
, removeSelf
... makes it more powerful, would it not?
UPDATE
It seems already that the consensus is going to be 'implement one your own'. But I am thinking 'too much boilerplate code' that can be avoided without overly risking exposing node management innards.
I hope that eventually someone will stumble upon this, and tell me that there is something that does exactly offer that.
add
doesn't work the way you think it does. (see grepcode).add
- see correct grepcode, where it does exactly what I think it does. I am refering to theadd(index,element)
method, not theadd(element)
method.