Chapter9-part2-Iterators
Chapter9-part2-Iterators
Programming II (CS300)
MOUNA KACEM
[email protected]
Iterable Interface and Iterators 2
Collection<T> Interface
Iterators
Iterable Interface
For-each loop
Collection Interface 3
data 10 20 15 30 25 5
ArrayList – for instance ListADT<Integer> data = new ArrayList<>(); // add elements to the list
0 1 2 3 4 5 6 7 … data.length-1
instanceof data
ArrayList 10 20 15 30 25 5 null null … null
size: 6
A chain of linked nodes given its head (Singly linked list) – LinkedNode<T> head
instanceof 0 1 2 3 4 5
LinkedList
10 20 15 30 25 5 X
head
tail
size: 6
Traverse a Collection of Objects 6
Collection of Objects
Iterator
an object that can be used to traverse a collection
Iterators are defined by a parameterized interface named Iterator<T>
@see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Iterator.html
Different types of collections have iterators that are implemented in
different ways, but all iterators are used in the same way
An iterator provides a good way to iterate over a generic set type
Generic Way to Traverse a Collection of Objects 10
0 1 2 3 4
10 20 30 40 50
itr.next()
10
Generic Way to Traverse a Collection of Objects 12
Iterator <Integer> itr = new SomeIterator<Integer>();
0 1 2 3 4
10 20 30 40 50
itr.next() itr.next()
10 20
Generic Way to Traverse a Collection of Objects 13
Iterator <Integer> itr = new SomeIterator<Integer>();
0 1 2 3 4
10 20 30 40 50
0 1 2 3 4
10 20 30 40 50
0 1 2 3 4
10 20 30 40 50
0 1 2 3 4
10 20 30 40 50
Question
17
List Abstract Data Type 18
int index = 0;
while(index < list.size())
{
T next = list.get(index);
index++;
// use next
}
Question
Complete the missed line of code within the following ListIterator.hasNext() 21
method to implement appropriately its behavior.
Complete the missed line of code within the following ListIterator.next() 22
method to implement appropriately its behavior.
T next = list.get(index);
index++;
return next;
Iterable interface 23
A.
B.
C.
D.
E.
For each loop 25
Syntax
for (<ElementType> <variable> : <collection>){
<loop body> // Does not have any effect on the value of <variable> reference
}
A for-each loop can be used to traverse a collection IF AND ONLY IF the
collection implements the java.lang.Iterable interface
The Iterable interface provides a clean and elegant way to code the
iteration functionality
In java, we can use the for-each loop to traverse an array
For each loop 26
The for each loop can be used to iterate over a collection if and only if
the collection implements the java.lang.Iterable interface
The Iterable.iterator() method must be overridden
The Iterable.iterator() method returns a new reference to an iterator
(Iterator<T>) which can be used to iterate through the collection
The for each loop cannot be used to make change to the contents of a
collection.
Use a while loop or a classic for loop instead if you need to change the
content of the list