1 Iterators "First things first, but not necessarily in that order " -Dr. Who CS 221 - Computer Science II.

Slides:



Advertisements
Similar presentations
Computer Science 209 Software Development Iterators.
Advertisements

©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.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Grouping Objects 3 Iterators, collections and the while loop.
Week 10 Recap CSE 115 Spring For-each loop When we have a collection and want to do something to all elements of that collection we use the for-each.
Generic Classes and 'for each' Loops List zoo = new ArrayList (); // … add several Animals to the zoo for (Animal animal : zoo) // do something with animal.
CS 280 Data Structures Professor John Peterson. Project 9 Questions? IS280.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
1 ADTs, Collection, Iterable/Iterator Interfaces Collections and the Java Collections API The Collection Interface and its Hierarchy The Iterable and Iterator.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 1 Topic 12 ADTS, Data Structures, Java Collections and Generic Data Structures.
1 Topic 8 Iterators "First things first, but not necessarily in that order " -Dr. Who.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CS 307 Fundamentals of Computer ScienceIterators 1 Topic 14 Iterators "First things first, but not necessarily in that order " -Dr. Who.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Iterator COMP 401, Spring 2013 Lecture 07 1/31/2013.
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.
Arrays And ArrayLists - S. Kelly-Bootle
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Today’s Agenda  Generic  Iterators CS2336: Computer Science II.
Using Iterators Trey Chandler Burlington Williams High School Mr. Langner’s Class,
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
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.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
List Interface and Linked List Mrs. Furman March 25, 2010.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Functional Processing of Collections (Advanced) 6.0.
1 Iterator Pattern (A Behavioral Pattern) Prepared by: Neha Tomar.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
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.
Linked Data Structures
EKT472: Object Oriented Programming
Software Development Iterators
Functional Processing of Collections (Advanced)
Outline Altering flow of control Boolean expressions
"First things first, but not necessarily in that order " -Dr. Who
Lecture 26: Advanced List Implementation
"First things first, but not necessarily in that order." -Dr. Who
Object Oriented Programming in java
Interator and Iterable
"First things first, but not necessarily in that order " -Dr. Who
JCF Collection classes and interfaces
"First things first, but not necessarily in that order " -Dr. Who
slides created by Alyssa Harding
TCSS 143, Autumn 2004 Lecture Notes
Presentation transcript:

1 Iterators "First things first, but not necessarily in that order " -Dr. Who CS Computer Science II

2 Iterators  ArrayList is part of the Java Collections Framework  Collection is an interface that specifies the basic operations every collection should have  Some Collections don’t have a definite order –Sets, Maps, Graphs  How to access all the items in a Collection with no specified order?

CS Computer Science II 3 Iterator Interface  An iterator object is a “one shot” object –it is designed to go through all the elements of a Collection once –if you want to go through the elements of a Collection again you have to get another iterator object  Iterators are obtained by calling a method from the Collection

CS Computer Science II 4 Iterator Iterface Methods  The Iterator interface specifies 3 methods: boolean hasNext() //returns true if this iteration has more elements E next() //returns the next element in this iteration //pre: hastNext() void remove() /*Removes from the underlying collection the last element returned by the iterator. pre: This method can be called only once per call to next. After calling, must call next again before calling remove again. */

Question 1  Which of the following produces a syntax error? ArrayList list = new ArrayList (); Iterator it1 = new Iterator(); // I Iterator it2 = new Iterator(list); // II Iterator it3 = list.iterator(); // III A. I B. II C. III D. I and II E. II and III CS Computer Science II 5

6 Iterator  Imagine a fence made up of fence posts and rail sections fenceposts rails

CS Computer Science II 7 Fence Analogy  The iterator lives on the fence posts  The data in the collection are the rails  Iterator created at the far left post  As long as a rail exists to the right of the Iterator, hasNext() is true iterator object

CS Computer Science II 8 Fence Analogy ArrayList names = new ArrayList (); names.add(“Jan”); names.add(“Levi”); names.add(“Tom”); names.add(“Jose”); Iterator it = names.iterator(); int i = 0; “Jan” “Levi” “Tom” “Jose”

CS Computer Science II 9 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 1, prints out Jan “Jan” “Levi” “Tom” “Jose” first call to next moves iterator to next post and returns “Jan”

CS Computer Science II 10 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 2, prints out Levi “Jan” “Levi” “Tom” “Jose”

CS Computer Science II 11 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 3, prints out Tom “Jan” “Levi” “Tom” “Jose”

CS Computer Science II 12 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 4, prints out Jose “Jan” “Levi” “Tom” “Jose”

CS Computer Science II 13 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // call to hasNext returns false // while loop stops “Jan” “Levi” “Tom” “Jose”

CS Computer Science II 14 Typical Iterator Pattern public void printAll(Collection list) { Iterator it = list.iterator(); while( it.hasNext() ) { Object temp = it.next(); System.out.println( temp ); }

Question 2  What is output by the following code? ArrayList list; list = new ArrayList (); list.add(3); list.add(5); Iterator it = list.iterator(); System.out.println(it.next()); A.3 B. 5 C D. 3 3 E. 3 5 CS Computer Science II 15

CS Computer Science II 16 remove method  An Iterator can be used to remove things from the Collection  Can only be called once per call to next() public void removeWordsOfLength(int len) { Iterator it = myList.iterator while( it.hasNext() ) { String temp = it.next(); if(temp.length() == len) it.remove(); } // original list = [“dog”, “cat”, “hat”, “sat”] // resulting list after removeWordsOfLength(3) ?

CS Computer Science II 17 Question 3 public void printTarget(ArrayList names, int len) { Iterator it = names.iterator(); while( it.hasNext() ) if( it.next().length() == len ) System.out.println( it.next() ); } Given names = [“Jan”, “Ivan”, “Tom”, “George”] and len = 3 what is output by the printTarget method? A.Jan Ivan Tom George B.Jan Tom C.Ivan George D.No output due to syntax error E.No output due to runtime error

CS Computer Science II 18 The Iterable Interface  A related interface is Iterable  One method in the interface: public Iterator iterator()  Why?  Anything that implements the Iterable interface can be used in the for each loop. ArrayList list; //code to create and fill list int total = 0; for( int x : list ) total += x;

CS Computer Science II 19 Iterable  If you simply want to go through all the elements of a Collection (or Iterable thing) use the for-each loop –hides creation of the Iterator public void printAllOfLength(ArrayList names, int len) { //pre: names != null, names only contains Strings //post: print out all elements of names equal in // length to len for(String s : names) { if( s.length() == len ) System.out.println( s ); }

CS Computer Science II 20 Iterable  Can also use typical for loop for (Iterator itr = list.iterator(); itr.hasNext(); ) { E element = iter.next(); // can call methods of element... }

CS Computer Science II 21 Implementing an Iterator  Implement an Iterator for our GenericList class –Nested Classes –Inner Classes –Example of encapsulation –checking precondition on remove –does our GenricList need an Iterator?

CS Computer Science II 22 Comodification  If a Collection ( ArrayList ) is changed while an iteration via an iterator is in progress an Exception will be thrown the next time the next() or remove() methods are called via the iterator ArrayList names = new ArrayList (); names.add(“Jan”); Iterator it = names.iterator(); names.add(“Andy”); it.next(); // exception will occur here