Lecture 15: More Iterators

Slides:



Advertisements
Similar presentations
Chapter 10 Introduction to Arrays
Advertisements

CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
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.
Problem Of The Day  Decipher the following phrase: STANDS 0 _
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
EECE 310: Software Engineering Iteration Abstraction.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
CSC 212 – Data Structures Lecture 37: Course Review.
ICOM 4035 – Data Structures Lecture 3 – Bag ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
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.
CSC 212 – Data Structures Lecture 17: Stacks. Question of the Day Move one matchstick to produce a square.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
ICOM 4035 – Data Structures Lecture 4 – Set ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
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.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Arrays Chapter 7.
Lecture 5: Test-Driven Development Basics
Data Abstraction: The Walls
EECE 310: Software Engineering
Some Eclipse shortcuts
CSE 116/504 – Intro. To Computer Science for Majors II
CSE 116/504 – Intro. To Computer Science for Majors II
CSE 116/504 – Intro. To Computer Science for Majors II
CSE 116/504 – Intro. To Computer Science for Majors II
Lecture 23: Doubly Linked List
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Introduction to Data Structures
Java Programming Language
Writing Methods AP Computer Science A.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Advanced Java Programming
Generic programming in Java
Dynamic Data Structures and Generics
Building Java Programs
OO Design with Inheritance
"First things first, but not necessarily in that order " -Dr. Who
Dynamic Data Structures and Generics
CS 2430 Object Oriented Programming and Data Structures I
Dr. Sampath Jayarathna Cal Poly Pomona
Suggested self-checks: Section 7.11 #1-11
Java Programming Language
CSC 143 Java Linked Lists.
Data Structures & Algorithms
slides created by Marty Stepp
slides created by Alyssa Harding
Data Structures & Algorithms
Podcast Ch21d Title: Hash Class Iterators
CSE 143 Lecture 21 Advanced List Implementation
Review for Midterm 3.
Presentation transcript:

Lecture 15: More Iterators CSE 116/504 – Intro. To Computer Science for Majors II Lecture 15: More Iterators

Announcements Project phase #1 due TODAY at 11:59PM Submit in Autolab; please list partners in submission(?) Self & peer evaluations this week in your recitations I can override individual scores, but will need evidence Test #1 in 8 days (Tuesday, October 10th) The first test will cover material through this week Let me know of conflicts – make-up is following day

Implementing the Iterator Iterator class needs access to ADT’s internal fields Implementation-less ADT concept must be violated Code specific to implementation and not reusable All good OO design concepts get thrown out window

Implementing the Iterator Iterator class needs access to ADT’s internal fields Implementation-less ADT concept must be violated Code specific to implementation and not reusable All good OO design concepts get thrown out window

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection 1

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection Convince your neighbor your answer is correct

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection 1

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection Nope; for-each uses Iterable (and that is mostly side effect)

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection null is valid element; Iterator just provides access

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection Not just Collections; Iterator can be created for anything

Which Is Iterator’s Purpose? 1-by-1 access to data independent of source Simplify coding using for-each loops Find all non-null elements in Collection Access all elements in a Collection Iterator.next() returns next item from source; Iterator can be written to draw from any source

Iterable holds data processed with for-each loop Iterable Key Concept #1 Iterable holds data processed with for-each loop

Iterator accesses data BUT separate class Iterator Key Concept #1 Iterator accesses data BUT separate class

Algorithm For ALL Iterators Algorithm hasNext() if cursor will access a valid location return true else return false endif end

Algorithm For ALL Iterators Algorithm hasNext() if cursor will access a valid location return true else return false endif end

What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over 1

Convince your neighbor your answer is correct What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over Convince your neighbor your answer is correct

What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over 1

What if data is not in an array? What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over What if data is not in an array?

Value accesses data returned by NEXT call to next() What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over Value accesses data returned by NEXT call to next()

May not be an array; Cursor used to access data from source What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over May not be an array; Cursor used to access data from source

Cursor used to access data; Cursor details depend on data source What is Role of Cursor? int equal to array index Way to access data to be returned by next() Data which was just returned by next() Array which holds the data we are iterating over Cursor used to access data; Cursor details depend on data source

Iterator’s cursor used to access next value Iterator Key Concept #2 Iterator’s cursor used to access next value

Iterator Principles Independent element-by-element data access next() returns an element; each call provides new value Using Iterator methods, data source unimportant public interface Iterator<E> { boolean hasNext(); E next() throws NoSuchElementException; void remove() throws UnsupportedOperationException; }

Iterator Principles Independent element-by-element data access next() returns an element; each call provides new value Using Iterator methods, data source unimportant public interface Iterator<E> { boolean hasNext(); E next() throws NoSuchElementException; void remove() throws UnsupportedOperationException; }

Algorithm For (almost) ALL Iterators Algorithm next() if hasNext() then E retVal = value at cursor’s location Advance cursor to refer to next location return retVal else // Panic – we cannot do this! endif end

Algorithm For (almost) ALL Iterators Algorithm next() if hasNext() then E retVal = value at cursor’s location Advance cursor to refer to next location return retVal else throw new NoSuchElementException(); endif end

2 Varieties of Exceptions Checked Exception Unchecked Exception Use for fixable errors Java forces methods to consider them Only useful if possibly fixable Subclass of Exception throws must list uncaught Will crash program if uncaught Use when royally screwed Java lets methods ignore these if they want Helps when error cannot be fixed Subclass of RuntimeException Can be listed in throws Will crash program if uncaught

2 Varieties of Exceptions Checked Exception Unchecked Exception Use for fixable errors Java forces methods to consider them Only useful if possibly fixable Subclass of Exception throws must list uncaught Will crash program if uncaught Use when royally screwed Java lets methods ignore these if they want Helps when error cannot be fixed Subclass of RuntimeException Can be listed in throws Will crash program if uncaught

If Exception Thrown, What Type? double sumPos(Iterator<Double> it){ double sum = 0; while (it.hasNext()) { if (it.next() > 0) { sum += it.next(); } } return sum; } Checked Exception Unchecked Exception Throwable Exception Thread Exception Do this using a show of hands – the question is NOT in TopHat (it could be, but not for time purposes) 1

If Exception Thrown, What Type? double sumPos(Iterator<Double> it){ double sum = 0; while (it.hasNext()) { if (it.next() > 0) { sum += it.next(); } } return sum; } Cannot be fixed Checked Exception Unchecked Exception Throwable Exception Thread Exception

If Exception Thrown, What Type? double sumPos(Iterator<Double> it){ double sum = 0; while (it.hasNext()) { if (it.next() > 0) { sum += it.next(); } } return sum; } Cannot be fixed & no throws provided Checked Exception Unchecked Exception Throwable Exception Thread Exception

Separate class but accesses private fields Problem Separate class but accesses private fields

Separate But Not Independent Most often adopt clean solution using inner class Inner class is independent class & follows Java rules Parameters, instance variables, & locals can use as type Must instantiate (new InnerClassName()) before use Can be used as return value & usable beyond outer class

Separate But Not Independent Most often adopt clean solution using inner class Inner class is independent class & follows Java rules Parameters, instance variables, & locals can use as type Must instantiate (new InnerClassName()) before use Can be used as return value & usable beyond outer class BUT

Separate But Not Independent Most often adopt clean solution using inner class Inner class is independent class & follows Java rules Parameters, instance variables, & locals can use as type Must instantiate (new InnerClassName()) before use Can be used as return value & usable beyond outer class BUT Inner class can use outer classes private fields

Declaring Inner Class Inner classes declared like normal Java classes But class declaration must be INSIDE main (outer) class Filename unchanged: still OuterClassName.java Typical Java class rules still apply to inner classes Inheritance (subclass and interface) is perfectly legal Can have instance variables, constructors, & methods Static & instance-based members can be declared Inner class’s methods same as other Java methods

Inner Class Access

Inner Class Access Can directly accesses own instance variables Just a normal Java class, so should not be surprise But (& this is change) also accesses outer class’s fields Protections do not matter, access is always allowed Like gut bacteria, permission only in 1 direction Inner class protections limit outer class actions This is by design: inner classes support outer class

Inner Class Access public class ArrayMultiSet<E> /* cut for space */ { private E[] _store; private int _size; private long _modCount; // Code exists here, but not shown due to space limits public class AMSIterator implements Iterator<E>{ private int cursor; // More code is here, but not shown to fit on screen public boolean hasNext() { return (cursor < _size); } } // More from ArrayMultiSet here; not shown due to screen space }

Instantiating Inner Classes public class ArrayMultiSet<E> /* cut for space */ { private E[] _store; private int _size; private long _modCount; // Code exists here, but not shown due to space limits public Iterator<E> iterator() { return new AMSIterator(); } public class AMSIterator implements Iterator<E>{ // More code is here, but not shown to fit on screen } // More from ArrayMultiSet here; not shown due to screen space }

Fill In the Blank assertTrue Cannot know -- behavior is undefined ArrayMultiSet<Integer> ams = new ArrayMultiSet<Integer>(); ams.add(2); Iterator<Integer> it=ams.iterator(); assertEquals(2, it.next()); ams.add(3); _____________(it.next()==3); assertTrue Cannot know -- behavior is undefined None of the above – code will crash Ungraded; only being asked once. 1

Could return 3; added 3 to _store at the index after where 2 is found Fill In the Blank ArrayMultiSet<Integer> ams = new ArrayMultiSet<Integer>(); ams.add(2); Iterator<Integer> it=ams.iterator(); assertEquals(2, it.next()); ams.add(3); _____________(it.next()==3); assertTrue Cannot know -- behavior is undefined None of the above – code will crash Could return 3; added 3 to _store at the index after where 2 is found

Fill In the Blank assertTrue Cannot know -- behavior is undefined ArrayMultiSet<Integer> ams = new ArrayMultiSet<Integer>(); ams.add(2); Iterator<Integer> it=ams.iterator(); assertEquals(2, it.next()); ams.add(3); _____________(it.next()==3); assertTrue Cannot know -- behavior is undefined None of the above – code will crash

Fill In the Blank assertTrue Cannot know -- behavior is undefined ArrayMultiSet<Integer> ams = new ArrayMultiSet<Integer>(); ams.add(2); Iterator<Integer> it=ams.iterator(); assertEquals(2, it.next()); ams.add(3); _____________(it.next()==3); assertTrue Cannot know -- behavior is undefined None of the above – code will crash

Behavior undefined; any of these could be correct Fill In the Blank ArrayMultiSet<Integer> ams = new ArrayMultiSet<Integer>(); ams.add(2); Iterator<Integer> it=ams.iterator(); assertEquals(2, it.next()); ams.add(3); _____________(it.next()==3); assertTrue Cannot know -- behavior is undefined None of the above – code will crash Behavior undefined; any of these could be correct

Fail-fast Iterator Iterator results after data changed could be wrong

Fail-fast Iterator Iterator results after data changed could be wrong May lead to bad outcomes & unpredictable results Best avoid blame; must make certain Not Your Fault™ Idea behind fail-fast Iterators – avoid potential mistakes Fail-fast Iterators track data’s modification count Count increases each time data changed in program When it is created, Iterator records modification count Error in next() when different saved & current count

Fail-fast Iterator Iterator results after data changed could be wrong May lead to bad outcomes & unpredictable results Best avoid blame; must make certain Not Your Fault™ Idea behind fail-fast Iterators – avoid potential mistakes Fail-fast Iterators track data’s modification count Count increases each time data changed in program When it is created, Iterator records modification count Error in next() when different saved & current count

Fail-Fast Iterator Skeleton public class ArrayMultiSet<E> /* cut for space */ { private E[] _store; private int _size; private long _modCount; // Code exists here, but not shown due to space limits public class AMSIterator implements Iterator<E>{ private int cursor; private long expectedModCount; // More code is here, but not shown to fit on screen public AMSIterator() { cursor = 0; expectedModCount = _modCount; } } }

Fail-Fast Iterator Skeleton public class ArrayMultiSet<E> /* cut for space */ { private E[] _store; private int _size; private long _modCount; // Code exists here, but not shown due to space limits public class AMSIterator implements Iterator<E>{ private int cursor; private long expectedModCount; // More code is here, but not shown to fit on screen public AMSIterator() { cursor = 0; expectedModCount = _modCount; } } }

_modCount & expectedModCount? Similar fields found in most fail-fast Collections Counts changes in elements that comprise the ADT Updated once per change, even if change to mult. data Provide versioning for Iterator to use in its checks expectedModCount is used by Iterator to fail Assigned to _modCount in Iterator’s constructor expectedModCount checked against _modCount Values differ once change in elements occurs

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray() 1

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray() Convince your neighbor your answer is correct

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray() 1

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray()

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray()

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray()

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray()

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray()

ArrayMultiSet Methods Changed? add() remove() contains() fromArray() toArray()

How To Use _modCount Increment _modCount when elements changed After element added to backing store in add() Success in remove() deleting element from ADT Having ADT elements replaced via fromArray() Any changes that might create mistakes in Iterator

How To Use _modCount Increment _modCount when elements changed After element added to backing store in add() Success in remove() deleting element from ADT Having ADT elements replaced via fromArray() Any changes that might create mistakes in Iterator

Fail-Fast Iterators Algorithm next() if hasNext() then E retVal = value at cursor’s location Advance cursor to refer to next location return retVal else throw new NoSuchElementException(); endif end

Fail-Fast Iterators Algorithm next() if hasNext() then if expectedModCount == _modCount then E retVal = value at cursor’s location Advance cursor to refer to next location return retVal else throw new ConcurrentModificationException(); endif else throw new NoSuchElementException(); endif end

Iterable holds data processed with for-each loop Iterable Key Concept #1 Iterable holds data processed with for-each loop

Iterator accesses data BUT separate class Iterator Key Concept #1 Iterator accesses data BUT separate class

Iterator’s cursor used to access next value Iterator Key Concept #2 Iterator’s cursor used to access next value

NO! For Next Lecture Section 3.1 & web page reading for Wednesday Is all code really equal? How can we figure out which is faster? Week #6 weekly assignment due Monday Today is new, rest of the week reviews for test #1 NO!