Using Iterators Trey Chandler Burlington Williams High School Mr. Langner’s Class,
List Traversal What is it? –A way of moving through linked data structures node by node –It can be used with plenty of classes, such as LinkedList, Set, etc.
Methods of Traversal Using the getNext() method of the ListNode class creating a current instance variable that refers to a particular node in a linked structure
But, There are some problems!!!!!!!!! For Example, what happens if you want to access the list in two places simultaneously?
The solution is... The Iterator!
So, What is an iterator? Iterator is an iterface in the java.util package. Iterators advance through the nodes of a linked data structure one by one
Methods of Iterator boolean hasNext() –returns true if there are more elements to be examined, false otherwise Object next() –returns the next element void remove() –removes the last element returned by next
hasNext() Current In this case hasNext() would return true
hasNext() Current In this case hasNext() would return false
next() The first call to next() results in the first element of the the data structure. To begin with, the list looks like this Current
next() When next is called, it looks like this Current
next() When next is called again, it looks like this Current
next() When next is called again, it looks like this Current If next is called one more time, an exception is thrown
remove() remove() can only be used once per call to next() next() must be called at least once before remove() is called If next() is not called before, an exception is thrown.
remove() If a the current node is position one (meaning next() would result in pos. 2) and remove() is called... Current 12 3
remove() The linked list would look like this Current 23
ListIterator ListIterator is an extension of the Iterator interface It has two additional methods: void set(Object o) and add(Object o)
set(Object o) Sets the current node to Object o. For example: Current xyz With this LinkedList, a call to set(w) would produce...
This! Current x w z
add(Object o) Adds a node immediately before what would be the result of next() Current x w z For example, a call of add(v) would produce...
This! Current x wzv
Creating an instance interator Oftentimes, an instance of Iterator of ListIterator can be created by using the iterator() or listIterator() method of a class. For LinkedList g, Iterator x = g.iterator() would produce an instance of Iterator called x that begins at g’s first node. On your AP Test, refer to the java subset to see which classes have these methods.
Bibliography Barron’s How to Prepare for the AP Computer Science Advanced Placement Examination Java Version util/Iterator.html