CS 307 Fundamentals of Computer ScienceIterators 1 Topic 14 Iterators "First things first, but not necessarily in that order " -Dr. Who.

Slides:



Advertisements
Similar presentations
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
Advertisements

CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Grouping Objects 3 Iterators, collections and the while loop.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
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.
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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.
Iterators CS 367 – Introduction to Data Structures.
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.
Recursion Examples Fundamentals of CS Case 1: Code /* Recursion: Case 1 */ #include void count (int index); main () { count (0); getchar(); } void count.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Data structures Abstract data types Java classes for Data structures and ADTs.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
1 Iterators "First things first, but not necessarily in that order " -Dr. Who CS Computer Science II.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
CS 307 Fundamentals of Computer ScienceLinked Lists 1 Topic 14 Linked Lists "All the kids who did great in high school writing pong games in BASIC for.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
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.
CS1101: Programming Methodology
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.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
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.
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.
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
Iterators.
Objects First with Java CITS1001 week 4
Lecture 20: Wrapper Classes and More Loops
Software Development Iterators
Topic 6 Generic Data Structures
Top Ten Words that Almost Rhyme with “Peas”
Outline Altering flow of control Boolean expressions
"First things first, but not necessarily in that order " -Dr. Who
CSE 143 Lecture 27: Advanced List Implementation
Iterator.
Lecture 26: Advanced List Implementation
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
"First things first, but not necessarily in that order." -Dr. Who
Object Oriented Programming in java
String and Lists Dr. José M. Reyes Álamo.
Interator and Iterable
"First things first, but not necessarily in that order " -Dr. Who
"First things first, but not necessarily in that order " -Dr. Who
Introduction to Computer Science
slides created by Alyssa Harding
Introduction to Java Collection
Presentation transcript:

CS 307 Fundamentals of Computer ScienceIterators 1 Topic 14 Iterators "First things first, but not necessarily in that order " -Dr. Who

CS 307 Fundamentals of Computer ScienceIterators 2 A Question public class WordList { private ArrayList myList; // pre: none // post: all words that are exactly len // characters long have been removed from // this WordList with the order of the // remaining words unchanged public void removeWordsOfLength(int len){ for(int i = 0; i < myList.size(); i++){ if( myList.get(i).length() == len ) myList.remove(i); }

Attendance Question 1  When does method removeWordsOfLength work as intended? A.Always B.Sometimes C.Never // original list = [“dog”, “cat”, “hat”, “sat”] // resulting list after removeWordsOfLength(3) ? CS 307 Fundamentals of Computer ScienceIterators 3

CS 307 Fundamentals of Computer ScienceIterators 4 The Remove Question  Answer? public void removeWordsOfLength(int len) { Iterator it = myList.iterator(); while( it.hasNext() ) if( it.next().length() == len ) it.remove(); } // original list = [“dog”, “cat”, “hat”, “sat”] // resulting list after removeWordsOfLength(3) ?

CS 307 Fundamentals of Computer ScienceIterators 5  ArrayList is part of the Java Collections framework  Collection is an interface that specifies the basic operations every collection (data structure) 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 307 Fundamentals of Computer ScienceIterators 6 Access All Elements - ArrayList public void printAll(ArrayList list){ for(int i = 0; i < list.size(); i++) System.out.println(list.get(i)); }  How do I access all the elements of a Set? The elements don’t have an index.  Iterator objects provide a way to go through all the elements of a Collection, one at a time

CS 307 Fundamentals of Computer ScienceIterators 7 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 307 Fundamentals of Computer ScienceIterators 8 Iterator Methods  The Iterator interface specifies 3 methods: boolean hasNext() //returns true if this iteration has more elements Object 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. */

Attendance Question 2  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 307 Fundamentals of Computer ScienceIterators 9

CS 307 Fundamentals of Computer ScienceIterators 10 Typical Iterator Pattern public void printAll(ArrayList list){ Iterator it = list.iterator(); Object temp; while( it.hasNext() ) { temp = it.next(); System.out.println( temp ); }

CS 307 Fundamentals of Computer ScienceIterators 11 Typical Iterator Pattern 2 public void printAll(ArrayList list){ Iterator it = list.iterator(); while( it.hasNext() ) System.out.println( it.next() ); } // go through twice? public void printAllTwice(ArrayList list){ Iterator it = list.iterator(); while( it.hasNext() ) System.out.println( it.next() ); it = list.iterator(); while( it.hasNext() ) System.out.println( it.next() ); }

CS 307 Fundamentals of Computer ScienceIterators 12 A Picture of an Iterator  Imagine a fence made up of fence posts and rail sections fenceposts rails

CS 307 Fundamentals of Computer ScienceIterators 13 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 307 Fundamentals of Computer ScienceIterators 14 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 307 Fundamentals of Computer ScienceIterators 15 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 307 Fundamentals of Computer ScienceIterators 16 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 2, prints out Levi “Jan” “Levi” “Tom” “Jose”

CS 307 Fundamentals of Computer ScienceIterators 17 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 3, prints out Tom “Jan” “Levi” “Tom” “Jose”

CS 307 Fundamentals of Computer ScienceIterators 18 Fence Analogy while( it.hasNext() ) { i++; System.out.println( it.next() ); } // when i == 4, prints out Jose “Jan” “Levi” “Tom” “Jose”

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

Attendance Question 3  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 307 Fundamentals of Computer ScienceIterators 20

CS 307 Fundamentals of Computer ScienceIterators 21 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

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

CS 307 Fundamentals of Computer ScienceIterators 23 Common Iterator Error 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 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?

CS 307 Fundamentals of Computer ScienceIterators 24 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 307 Fundamentals of Computer ScienceIterators 25 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 307 Fundamentals of Computer ScienceIterators 26 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?