Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

CHAPTER 4 Queues. Queue  The queue, like the stack, is a widely used data structure  A queue differs from a stack in one important way  A stack is.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
Computer Science 209 Software Development Iterators.
COMP 103 Linked Stack and Linked Queue.
COMP 121 Week 11: Linked Lists. Objectives Understand how single-, double-, and circular-linked list data structures are implemented Understand the LinkedList.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Iterators CS 367 – Introduction to Data Structures.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY.
COMP T2 Lecture 5 School of Engineering and Computer Science, Victoria University of Wellington Thomas Kuehne Maps, Stacks  Thomas Kuehne, Marcus.
Introduction to Analysing Costs 2015-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Rashina.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
David Streader Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Java Arrays and ArrayLists.
A review session 2013-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
18-1 Queues Data Structures and Design with Java and JUnit © Rick Mercer.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
COMP 121 Week 11: Linked Lists.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Computer Science 209 Software Development Inheritance and Composition.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
2014-T2 Lecture 27 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
Iteration Abstraction SWE Software Construction Fall 2009.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Iterator Summary Slides by Entesar Al-Mosallam adopted from Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Analysing Costs 2013-T2 Lecture 10 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Rashina.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
Iterators.
Software Development Iterators
JAVA COLLECTIONS LIBRARY
Software Development Inheritance and Composition
Implementing ArrayList Part 1
Iteration Abstraction
THURSDAY, OCTOBER 17 IN LAB
Programming in Java Lecture 11: ArrayList
(Java Collections Framework) AbstractSequentialList
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Iteration Abstraction
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

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

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

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…

 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 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);

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…

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

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()

An iterator for ArrayList 9 list nextIndex 0 9 ArrayList Iterator

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() }

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); }

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(); }

Example list nextIndex 5 removeable true

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 }

Multiple iterators list nextIndex 3 removeable true list nextIndex 5 removeable true

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())

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