Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Chapter 15 Lists. Chapter Scope Types of list collections Using lists to solve problems Various list implementations Comparing list implementations Java.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
Chapter 15 Lists.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
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.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Introduction to Collections – Stacks Modified
Lists Based on content from: Java Foundations, 3rd Edition.
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
COS 312 DAY 21 Tony Gauvin. Ch 1 -2 Agenda Questions? Last Capstone Progress reports due April 23 Assignment 6 Due Assignment 7 Posted – Chapters 15,
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
Chapter 8 Recursion Modified.
EECE 310: Software Engineering Iteration Abstraction.
Chapter 10-A Trees Modified
Chapter 13 Sets and Maps Modified. Chapter Scope The Java API set and map collections Using sets and maps to solve problems How the Java API implements.
LinkedList Many slides from Horstmann modified by Dr V.
CMSC 341 Linked Lists, Stacks and Queues. 8/3/2007 UMBC CMSC 341 LSQ 2 Implementing Your Own Linked List To create a doubly linked list as seen below.
CHAPTER 5 ArrayLists.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
© 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.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Linked Structures - Review Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Chapter 6 Lists Modified. Chapter Scope Types of lists Using lists to solve problems Various list implementations Comparing list implementations 6 - 2Java.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Iteration Abstraction SWE Software Construction Fall 2009.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
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.
CSE 143 Lecture 12: Sets and Maps reading:
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
CSE 1020: Exceptions and A multiclass application Mark Shtern 1-1.
Recursive Objects Singly Linked List (Part 2) 1. Operations at the head of the list  operations at the head of the list require special handling because.
COS 312 DAY 23 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone progress report Overdue Assignment 6 Over Due Assignment 7 (bonus) – Due May 11 – Will.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
Iterators.
Chapter 16 Iterators.
Chapter 6 Lists.
Chapter 4 Linked Structures - Stacks
Chapter 7 Iterators.
Java Software Structures: John Lewis & Joseph Chase
Linked Lists, Stacks and Queues Textbook Sections
Chapter 4 Linked Structures - Stacks
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
slides adapted from Marty Stepp
Dynamic Data Structures and Generics
Example: LinkedSet<T>
TCSS 143, Autumn 2004 Lecture Notes
CSE 143 Lecture 21 Advanced List Implementation
The command invocation protocol
CHAPTER 3: Collections—Stacks
Presentation transcript:

Chapter 7 Iterators Modified

Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve problems Iterator implementations 7 - 2Java Software Structures, 4th Edition, Lewis/Chase

Iterators Using various methods, the user could write code to access each element in a collection, but it would be slightly different for each collection An iterator is an object that allows the user to acquire and use each element in a collection It works with a collection, but is a separate object An iterator simplifies the classic step of processing elements in a collection 7 - 3Java Software Structures, 4th Edition, Lewis/Chase

Iterators There are two key interfaces in the Java API related to iterators: – Iterator – used to define an iterator – Iterable – used to define a collection that provides an iterator A collection is Iterable, which means it will provide an Iterator when requested 7 - 4Java Software Structures, 4th Edition, Lewis/Chase

Iterators The Iterator interface: The Iterable interface: 7 - 5Java Software Structures, 4th Edition, Lewis/Chase

Iterators Suppose myList is an ArrayList of Book objects Iterator itr = myList.iterator(); while (itr.hasNext()) System.out.println(itr.next()); The first line obtains the iterator, then the loop uses hasNext and next to access and print each book 7 - 6Java Software Structures, 4th Edition, Lewis/Chase

Iterators A for-each loop can be used for the same goal: for (Book book : myList) System.out.println(book); The for-each loop uses an iterator behind the scenes The for-each loop can be used on any object that is Iterable 7 - 7Java Software Structures, 4th Edition, Lewis/Chase

Iterators You may want to use an iterator explicitly if you don't want to process all elements – i.e., searching for a particular element You may also use an explicit iterator if you want to call the remove method The for-each loop does not give access to the iterator, so remove cannot be called 7 - 8Java Software Structures, 4th Edition, Lewis/Chase

Iterators You shouldn't assume that an iterator will deliver the elements in any particular order unless the documentation explicitly says you can Also, remember that an iterator is accessing the elements stored in the collection The structure of the underlying collection should not be changed while an iterator is being used Most iterators in the Java API are fail-fast, meaning they throw an exception if the collection is modified while the iterator is active 7 - 9Java Software Structures, 4th Edition, Lewis/Chase

Program of Study Revisited The ProgramOfStudy class was introduced in the last chapter It implements the Iterable interface Its iterator method returns the iterator provided by the list The POSGrades class uses a for-each loop to print courses with a grade of A or A Java Software Structures, 4th Edition, Lewis/Chase

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Represents a Program of Study, a list of courses taken and * planned, for an individual student. * Lewis and Chase 4.0 */ public class ProgramOfStudy implements Iterable, Serializable { … Java Software Structures, 4th Edition, Lewis/Chase

/** * Loads a serialized Program of Study from the specified file. * fileName the file from which the POS is read the loaded Program of Study IOException ClassNotFoundException */ public static ProgramOfStudy load(String fileName) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(fis); ProgramOfStudy pos = (ProgramOfStudy) ois.readObject(); ois.close(); return pos; } Java Software Structures, 4th Edition, Lewis/Chase

import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; /** * Demonstrates the use of an Iterable object (and the technique for reading * a serialzed object from a file). Lewis and Chase 4.0 */ public class POSGrades { /** * Reads a serialized Program of Study, then prints all courses in which * a grade of A or A- was earned. */ public static void main(String[] args) throws Exception { ProgramOfStudy pos = ProgramOfStudy.load("ProgramOfStudy"); System.out.println(pos); System.out.println("Classes with Grades of A or A-\n"); for (Course course : pos) { if (course.getGrade().equals("A") || course.getGrade().equals("A-")) System.out.println(course); } Java Software Structures, 4th Edition, Lewis/Chase

Program of Study Revisited Now we'll use an iterator to remove any course in the program of study that doesn't already have a grade Since the iterator's remove method will be used, we cannot use a for-each loop Java Software Structures, 4th Edition, Lewis/Chase

import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.Iterator; /** * Demonstrates the use of an explicit iterator. Lewis and Chase 4.0 */ public class POSClear { /** * Reads a serialized Program of Study, then removes all courses * that don't have a grade. */ public static void main(String[] args) throws Exception { ProgramOfStudy pos = ProgramOfStudy.load("ProgramOfStudy"); System.out.println(pos); System.out.println("Removing courses with no grades.\n"); Java Software Structures, 4th Edition, Lewis/Chase

Iterator itr = pos.iterator(); while (itr.hasNext()) { Course course = itr.next(); if (!course.taken()) itr.remove(); } System.out.println(pos); pos.save("ProgramOfStudy"); } Java Software Structures, 4th Edition, Lewis/Chase

Implementing Array-based Iterators Our ArrayList class contains a private inner class that defines an iterator for the list An iterator is an appropriate use for an inner class because of its intimate relationship with the outer class (the collection) It maintains a modification count that is initialized to the current number of elements in the collection If those counts get out of a sync, the iterator throws a ConcurrentModificationException Java Software Structures, 4th Edition, Lewis/Chase

/** * ArrayListIterator iterator over the elements of an ArrayList. */ private class ArrayListIterator implements Iterator { int iteratorModCount; int current; /** * Sets up this iterator using the specified modCount. * modCount the current modification count for the * ArrayList */ public ArrayListIterator() { iteratorModCount = modCount; current = 0; } Java Software Structures, 4th Edition, Lewis/Chase

/** * Returns true if this iterator has at least one more * element to deliver in the iteration. * true if this iterator has at least one more * element to deliver in the iteration ConcurrentModificationException if the * collection has changed while the iterator is in use */ public boolean hasNext() throws ConcurrentModificationException { if (iteratorModCount != modCount) throw new ConcurrentModificationException(); return (current < rear); } Java Software Structures, 4th Edition, Lewis/Chase

/** * Returns the next element in the iteration. If there are no * more elements in this iteration, a NoSuchElementException is * thrown. * the next element in the iteration NoSuchElementException if an element not found * exception occurs ConcurrentModificationException if the collection has * changed */ public T next() throws ConcurrentModificationException { if (!hasNext()) throw new NoSuchElementException(); current++; return list[current - 1]; } Java Software Structures, 4th Edition, Lewis/Chase

/** * The remove operation is not supported in this collection. * UnsupportedOperationException if the remove method is * called */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } Java Software Structures, 4th Edition, Lewis/Chase

Implementing Linked-Based Iterators Similarly, an iterator can use links Like the previous example, the LinkedListItertor class is implemented as a private inner class Java Software Structures, 4th Edition, Lewis/Chase

/** * LinkedIterator represents an iterator for a linked list of * linear nodes. */ private class LinkedListIterator implements Iterator { private int iteratorModCount; // no. of elements in the collection private LinearNode current; // the current position /** * Sets up this iterator using the specified items. * collection the collection the iterator will move over size the integer size of the collection */ public LinkedListIterator() { current = head; iteratorModCount = modCount; } Java Software Structures, 4th Edition, Lewis/Chase

/** * Returns true if this iterator has at least one more element * to deliver in the iteration. * true if this iterator has at least one more element * to deliver in the iteration ConcurrentModificationException if the collection has * changed while the iterator is in use */ public boolean hasNext() throws ConcurrentModificationException { if (iteratorModCount != modCount) throw new ConcurrentModificationException(); return (current != null); } Java Software Structures, 4th Edition, Lewis/Chase

/** * Returns the next element in the iteration. If there are no * more elements in this iteration, a NoSuchElementException is * thrown. * the next element in the iteration NoSuchElementException if the iterator is empty */ public T next() throws ConcurrentModificationException { if (!hasNext()) throw new NoSuchElementException(); T result = current.getElement(); current = current.getNext(); return result; } Java Software Structures, 4th Edition, Lewis/Chase

/** * The remove operation is not supported. * UnsupportedOperationException if the remove operation * is called */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } Java Software Structures, 4th Edition, Lewis/Chase