Download presentation
Presentation is loading. Please wait.
1
Lecture 15: More Iterators
CSE 116/504 – Intro. To Computer Science for Majors II Lecture 15: More Iterators
2
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
3
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
4
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
5
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
6
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
7
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
8
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)
9
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
10
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
11
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
12
Iterable holds data processed with for-each loop
Iterable Key Concept #1 Iterable holds data processed with for-each loop
13
Iterator accesses data BUT separate class
Iterator Key Concept #1 Iterator accesses data BUT separate class
14
Algorithm For ALL Iterators
Algorithm hasNext() if cursor will access a valid location return true else return false endif end
15
Algorithm For ALL Iterators
Algorithm hasNext() if cursor will access a valid location return true else return false endif end
16
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
17
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
18
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
19
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?
20
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()
21
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
22
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
23
Iterator’s cursor used to access next value
Iterator Key Concept #2 Iterator’s cursor used to access next value
24
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; }
25
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; }
26
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
27
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
28
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
29
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
30
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
31
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
32
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
33
Separate class but accesses private fields
Problem Separate class but accesses private fields
34
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
35
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
36
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
37
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
38
Inner Class Access
39
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
40
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 }
41
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 }
42
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
43
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
44
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
45
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
46
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
47
Fail-fast Iterator Iterator results after data changed could be wrong
48
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
49
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
50
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; } } }
51
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; } } }
52
_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
53
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray() 1
54
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray() Convince your neighbor your answer is correct
55
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray() 1
56
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray()
57
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray()
58
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray()
59
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray()
60
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray()
61
ArrayMultiSet Methods Changed?
add() remove() contains() fromArray() toArray()
62
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
63
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
64
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
65
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
66
Iterable holds data processed with for-each loop
Iterable Key Concept #1 Iterable holds data processed with for-each loop
67
Iterator accesses data BUT separate class
Iterator Key Concept #1 Iterator accesses data BUT separate class
68
Iterator’s cursor used to access next value
Iterator Key Concept #2 Iterator’s cursor used to access next value
69
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!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.