Download presentation
Presentation is loading. Please wait.
Published byJob West Modified over 8 years ago
1
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne Thomas Kuehne, Marcus Frean
2
RECAP Implementing the fundamental ArrayList methods AbstractList: ArrayList does not have to implement everything TODAY Iterators (necessary for the ‘for each...’-syntax) 2 RECAP-TODAY
3
How to provide ‘for each’ syntax? ArrayList 3 Iteration Example List mobs; mob = new ArrayList (); … for (Sheep c : mobs) { c.shear(); } How can we support the concise “for each” syntax for ArrayList? Where should iteration start, and what order should it go through the array? The answer is to provide an iterator for ArrayList. How do we implement it and make it part of ArrayList? BillyBaa Dolly…
4
In order to go through a collection of some type in a systematic manner, it is useful to have an iterator – i.e. an object that is an instance of a class that implements Iterator. The interface ensures that it provides two methods: hasNext() boolean next() E 4 The basic idea of iterators For our example, we need an “ArrayListIterator” (name is not important) that implements Iterator. A convenient location for this class is inside ArrayList, as a private inner class hidden from others has privileged access to ArrayList internals
5
5 Iterators in action for (Sheep c: mobs) { } …the compiler translates this into… Iterator iter = mobs.iterator(); while (iter.hasNext()) { Sheep c = iter.next(); } returns new ArrayListIterator (mobs);
6
All collection implementations must support iteration. How to ensure that they can all be iterated the same way? facilitate the “for each”-syntax? i.e., make sure they all offer “iterator()”? Need to ensure a class-specific implementation of Iterator exists. Sounds like a job for an Interface?! public interface Collection extends Iterable Iterable is an interface that stipulates just one method, i.e., iterator() that returns an Iterator for that class Every Collection implementation needs an Iterator 6 Let’s peek into the Java Collection library…
7
Iterators // Your code can get an iterator like this Iterator iter = myTasks.iterator(); List myTasks = new LinkedList (); iter Conforms to the interface Iterator Conforms to the interface List so… has methods add(), get(), set(), remove(), contains()… iterator() 7 so… has methods hasNext() next() remove() myTasks rarely used
8
Making Collections Iterable 8 Collection size() add() etc Collection size() add() etc extends List All Collection methods + some own List All Collection methods + some own ArrayList implements all List methods implements Iterator hasNext() next() remove() Iterator hasNext() next() remove() Iterable extends public Iterator iterator() ArrayListIterator implements all Iterator methods implements ? + the ONE method of Iterable ArrayList : ArrayListIterator sits inside as a private inner class public Iterator iterator()
9
An iterator for ArrayList 9 list nextIndex 0 9 ArrayList Iterator
10
In general, an iterator will need to be told which object it is attached to (hence “this”). In our case this isn’t strictly necessary, because we’re defining he iterator as a private inner class of ArrayList and hence have access anyhow. Inside iterator 10 /** Returns an iterator over the elements in the List */ public Iterator iterator() { return new ArrayListIterator (this); } /** Definition of the iterator for an ArrayList */ private class ArrayListIterator implements Iterator { // fields to store state (iteration progress) // constructor // hasNext() // next() // remove() }
11
Inside iterator 11.private class ArrayListIterator implements Iterator { private ArrayList list; // reference to the list object private int nextIndex; // the index of the next value to return private boolean removeable = false; // to support the “remove” operation /** Constructor */ private ArrayListIterator (ArrayList list) { this.list = list; nextIndex = 0; } /** Return true if the iteration has at least one more element to offer */ public boolean hasNext () { return (nextIndex < list.count); }
12
Inside iterator 12 /** Return next element in the List */ public E next () { if (nextIndex >= list.count) throw new NoSuchElementException(); E element = list.get(nextIndex); nextIndex++; ← increment and return return element; } /** Removes from the list the last element that was returned by the iterator (optional operation). */ public void remove() { throw new UnsupportedOperationException(); }
13
Example 13 0123456789 9 list nextIndex 5 removeable true
14
Improved versions of next() and remove() 14 /** Return next element in the List */ public E next () { if (nextIndex >= list.count) throw new NoSuchElementException(); removeable = true; ← for the remove method E element = list.get(nextIndex); nextIndex++; return element; } /** Removes from the underlying collection the last element returned by this * iterator. This method can be called only once per call to next(). */ public void remove() { if ( ! removeable ) throw new IllegalStateException(); removeable = false;← can only remove element once nextIndex--; ← put counter back to last item list.remove(nextIndex); ← remove last item }
15
Multiple iterators 15 0123456789 9 list nextIndex 3 removeable true list nextIndex 5 removeable true
16
Summary 16 Collections are iterable they are “marked” as Iterable and hence offer an iterator() method. Iterators supply collection elements sequentially they maintain iteration progress they are “marked” as Iterator and hence offer standard iteration methods (hasNext(), next(), remove())
17
Summary 17 Removing the last item returned is possible, but... ...multiple iterations in the presence of changes to a collection will lead to unexpected results Using an inner class made it easy to access ArrayList's private fields
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.