Question

I have a custom, generic, singly LinkedList which I built myself. I can add, remove etc to the List just fine. I'd like to implement the Java ListIterator to my class. How would I go about starting this? What methods do I need to add to my class? All I can find on the web is examples of using the ListIterator on the default Java LinkedList which is no good to me. Thanks!

Was it helpful?

Solution

You create a second class (usually a nested class of your linked list) that implements all the functions of the ListIterator interface. Note that some functions (like add and remove) are optional—you can just throw an UnsupportedOperationException. Your linked list class needs to implement the methods listIterator() and listIterator(int) to return an instance of your second class.

OTHER TIPS

You should implement the Iterator or the ListIterator interface.

Look for the methods that ListIterator has. You will need to make sure that your version of it has those same methods.

If you can, look for an Interface that ListIterator uses, and implement that interface.

For performance, you can implement ListIterator and keep a "backwards" version of your list as you iterate through it. This would emulate a doubly-linked list, but only for the iterator.

However, it's probably safer to just implement your linked list as a doubly-linked list underneath.

If it's a singly linked List, implementing ListIterator will be tricky (if not impossible), as it needs to navigate in both directions, which you can only implement by restarting from the head over and over again.

Either make your list double-linked, or you will have to throw UnsupportedOperationException on lots of methods. (Or live with O(n) performance in half the methods)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top