You are on page 1of 39

Algoritmos y Estructura de Datos: Iteradores

(Iterators)
Vincenzo Gulisano

Iterators

Which are the elements contained by the ADT?


We need something to visit all the elements

AED: Iterators

Iterators
Why iterators?

Pass over the elements of a collection

Iterator

Collection S
Current element
Next element

List

Current
Element
3

Next
Element
AED: Iterators

Iterators ADT
Iterator ADT
2 methods

hasNext(): True if theres an element after the


current position
next(): return the element

AED: Iterators

Iterators Java API

AED: Iterators

Iterators Java API

AED: Iterators

Iterators
How to get an iterator?

List

Iterator

AED: Iterators

Iterators

java.lang.Iterable (interface)

If a class implements this interface it provides


the method iterator()

AED: Iterators

Iterators Java API

AED: Iterators

Iterators
How to implement iterators?
First idea : Copy the elements into a queue

Queue
Collection

10

hasNext() = !isEmpty()
next() = deque()
AED: Iterators

Iterators

Using a queue

iterator() is costly (we have to copy all the elements)


Static, if the collection changes we need to copy it again

Better solution:

Point to the objects contained in the collection


Current
Element
Next
Element
Collection

11

AED: Iterators

Iterators

Complications

What if the collection changes while we iterate over the


elements?
has next?
yes

Current
Element

remove
last element
Current
Element

next

12

Exception!

AED: Iterators

Iterators

If the ADT is modified after the iterator has been


created

The Iterator is no more valid

Java API

13

AED: Iterators

Iterators

What about the ordering of the elements?

Current Next
Element Element
Current
Element

Next Element?

14

AED: Iterators

Iterators

Java API - LinkedList

Java API - HashSet

15

AED: Iterators

Iterators

the Java For-Each loop


List<int> values;

for(Iterator<int> i = values.iterator(); values.hasNext; )


{
int value = i.next();
System.out.println(value);
}

List<int> values;

for(int value : values)


{
System.out.println(value);
}
16

AED: Iterators

Iterators

List iterators

For Lists, more powerful than simple iterator


Do not point directly to an object, sits between them

Iterator

List Iterator

Current Next
Element Element

Prev Current Next


Element Element Element

17

AED: Iterators

Iterators

18

AED: Iterators

Iterators

add(E o)
hasNext()
hasPrevious()
next()
previous()
nextIndex()
previousIndex()
remove()
set()

19

AED: Iterators

Iterators

next()
previous()
Prev Current Next
Element Element Element

hasNext()
hasPrevious()
True

20

Current
Element

AED: Iterators

True

Iterators

nextIndex()
previousIndex()
Prev Current
Index Element

21

AED: Iterators

Next
Index

Iterators

remove()

on previous() or next()

Current
Element

set()

22

on previous() or next()

AED: Iterators

Example

NodePositionList<E>

package net.datastructures;
import java.util.Iterator;
public class NodePositionList<E> implements PositionList<E> {

public Iterator<E> iterator() { return new ElementIterator<E>(this); }


public static <E> String toString(PositionList<E> l) {
Iterator<E> it = l.iterator();
String s = "[";
while (it.hasNext()) {
s += it.next();
// implicit cast of the next element to String
if (it.hasNext())
s += ", ";
}
s += "]";
return s;
}
}

23

AED: Iterators

Example
NodePositionList<E>

implements

PositionList<E>
interface

extends

NodePositionList<String> x;
Iterator<E> i = x.iterator();

ElementIterator<E>

implements

Iterator<E>
interface

i.hasNext(); / i.next();

24

AED: Iterators

Iterable<E>
interface

Example - ElementIterator
public class ElementIterator<E> implements Iterator<E> {
protected PositionList<E> list; // the underlying list
protected Position<E> cursor; // the next position
public ElementIterator(PositionList<E> L) {
list = L;
cursor = (list.isEmpty()) ? null : list.first();
}
public boolean hasNext() {
return (cursor != null);
}
25

AED: Iterators

Example - ElementIterator
public E next() throws NoSuchElementException {
if (cursor == null)
throw new NoSuchElementException("No next element");
E toReturn = cursor.element();
cursor = (cursor == list.last()) ? null : list.next(cursor);
return toReturn;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("remove");
}
}

26

AED: Iterators

List Iterator

Example of List Iterator usage

Print content:

27

<-0-> A
A <-1-> B
B <-2-> C
C <-3-> D
D <-4-> E
E <-5->
AED: Iterators

List Iterator examples


LinkedList<String> myList = new LinkedList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
ListIterator<String> myListIterator = myList.listIterator();
int currentIndex = 0;
while (myListIterator.hasNext()) {
System.out.println(myListIterator.previous() + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
28

AED: Iterators

List Iterator examples


LinkedList<String> myList = new LinkedList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");

Exception in thread "main"


java.util.NoSuchElementException
at java.util.LinkedList$ListItr.previous(Unknown Source)

ListIterator<String> myListIterator = myList.listIterator();


int currentIndex = 0;
while (myListIterator.hasNext()) {
System.out.println(myListIterator.previous() + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
29

AED: Iterators

List Iterator examples


LinkedList<String> myList = new LinkedList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
ListIterator<String> myListIterator = myList.listIterator();
int currentIndex = 0;
while (myListIterator.hasNext()) {
String tempString = "";
if (myListIterator.hasPrevious())
tempString += myListIterator.previous();
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
30

AED: Iterators

List Iterator examples


LinkedList<String> myList = new LinkedList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
ListIterator<String> myListIterator = myList.listIterator();
int currentIndex = 0;
while (myListIterator.hasNext()) {
String tempString = "";
if (myListIterator.hasPrevious())
tempString += myListIterator.previous();
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
31

<-0-> A
A <-1-> A
A <-2-> A

A <-10000000-> A

AED: Iterators

List Iterator examples


LinkedList<String> myList = new LinkedList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
myList.add("E");
ListIterator<String> myListIterator = myList.listIterator();
int currentIndex = 0;
while (myListIterator.hasNext()) {
String tempString = "";
if (myListIterator.hasPrevious())
tempString += myListIterator.previous();
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
32

AED: Iterators

List Iterator examples


LinkedList<String> myList = new LinkedList<String>();
ListIterator<String> myListIterator = myList.listIterator();
System.out.println("Previous Index is : " + myListIterator.previousIndex());
System.out.println("Next Index is : " + myListIterator.nextIndex());
myListIterator.next();
System.out.println("After increasing current position by one element : ");
System.out.println("Previous Index is : " + myListIterator.previousIndex());
System.out.println("Next Index is : " + myListIterator.nextIndex());
myListIterator.previous();
System.out.println("After decreasing current position by one element : ");
System.out.println("Previous Index is : " + myListIterator.previousIndex());
System.out.println("Next Index is : " + myListIterator.nextIndex());
33

AED: Iterators

List Iterator Examples


Previous Index is : -1
Next Index is : 0
After increasing current position by one element :
Previous Index is : 0
Next Index is : 1
After decreasing current position by one element :
Previous Index is : -1
Next Index is : 0

34

AED: Iterators

List Iterator Examples


while (myListIterator.hasNext()) {
String tempString = "";
if (myListIterator.hasPrevious())
{
tempString += myListIterator.previous();
myListIterator.next();
}
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
35

AED: Iterators

List Iterator Examples


while (myListIterator.hasNext()) {

<-0-> A
A <-1-> B
B <-2-> C
C <-3-> D
D <-4-> E

String tempString = "";


if (myListIterator.hasPrevious())
{
tempString += myListIterator.previous();
myListIterator.next();
}
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;
}
36

AED: Iterators

List Iterator examples


int currentIndex = 0;
while (myListIterator.hasNext()) {
String tempString = "";
if (myListIterator.hasPrevious())
{
tempString += myListIterator.previous();
myListIterator.next();
}
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;

<-0-> A
A <-1-> B
B <-2-> C
C <-3-> D
D <-4-> E
E <-5->

}
System.out.println( myListIterator.previous() + " <-" + currentIndex + "-> ");
37

AED: Iterators

List Iterator examples

What if the list is empty?

38

Exception

AED: Iterators

List Iterator examples


int currentIndex = 0;
while (myListIterator.hasNext()) {
String tempString = "";
if (myListIterator.hasPrevious())
{
tempString += myListIterator.previous();
myListIterator.next();
}
System.out.println(tempString + " <-" + currentIndex
+ "-> " + myListIterator.next());
currentIndex++;

<-0-> A
A <-1-> B
B <-2-> C
C <-3-> D
D <-4-> E
E <-5->

}
if (myListIterator.hasPrevious())
{
System.out.println( myListIterator.previous() + " <-" + currentIndex + "-> ");
}
39

AED: Iterators

You might also like