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!