23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>in</strong>t total = 0;<br />

for (<strong>in</strong>t i : v)<br />

total += i;<br />

6.3.3 Implement<strong>in</strong>g Iterators<br />

One way to implement an iterator for a collection of elements is to make a<br />

"snapshot" of it <strong>and</strong> iterate over that. This approach would <strong>in</strong>volve stor<strong>in</strong>g the<br />

collection <strong>in</strong> a separate data structure that supports sequential access to its elements.<br />

For example, we could <strong>in</strong>sert all the elements of the collection <strong>in</strong>to a queue, <strong>in</strong><br />

which case method hasNext() would correspond to !isEmpty() <strong>and</strong> next()<br />

would correspond to enqueue(). With this approach, the method iterator()<br />

takes O(n) time for a collection of size n. S<strong>in</strong>ce this copy<strong>in</strong>g overhead is relatively<br />

costly, we prefer, <strong>in</strong> most cases, to have iterators operate on the collection itself, not<br />

a copy.<br />

In implement<strong>in</strong>g this direct approach, we need only to keep track of where <strong>in</strong> the<br />

collection the iterator's cursor po<strong>in</strong>ts. Thus, creat<strong>in</strong>g a new iterator <strong>in</strong> this case<br />

simply <strong>in</strong>volves creat<strong>in</strong>g an iterator object that represents a cursor placed just before<br />

the first element of the collection. Likewise, perform<strong>in</strong>g the next() method<br />

<strong>in</strong>volves return<strong>in</strong>g the next element, if it exists, <strong>and</strong> mov<strong>in</strong>g the cursor just past this<br />

element's position. Thus, <strong>in</strong> this approach, creat<strong>in</strong>g an iterator takes O(1) time, as do<br />

each of the iterator's methods. We show a class implement<strong>in</strong>g such an iterator <strong>in</strong><br />

Code Fragment 6.14, <strong>and</strong> we show <strong>in</strong> Code Fragment 6.15 how this iterator could<br />

be used to implement the iterator() method <strong>in</strong> the NodePositionList<br />

class.<br />

Code Fragment 6.14:<br />

Position List.<br />

An element iterator class for a<br />

344

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!