16-iterator-grammar - CSE 143 Lecture 16 Iterators;...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
CSE 143 Lecture 16 Iterators; Grammars reading: 11.1, 15.3, 16.5
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Iterators reading: 11.1; 15.3; 16.5
Background image of page 2
3 Examining sets and maps • elements of Java Set s and Map s can't be accessed by index – must use a "foreach" loop: Set<Integer> scores = new HashSet<Integer>(); for (int score : scores) { System.out.println("The score is " + score); } – Problem: foreach is read-only; cannot modify set while looping for (int score : scores) { if (score < 60) { // throws a ConcurrentModificationException scores.remove(score); } }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4 Iterators (11.1) iterator : An object that allows a client to traverse the elements of any collection. – Remembers a position, and lets you: • get the element at that position • advance to the next position • remove the element at that position 6 size 12 5 0 6 5 4 0 7 0 8 9 2 7 3 0 8 3 value 9 1 0 index list current element: 9 current index: 2 iterator set "the" "to" "from" "we" current element: "from" next element: "the" iterator
Background image of page 4
5 Iterator methods •Iterator interface in java.util – every collection has an iterator() method that returns an iterator over its elements Set<String> set = new HashSet<String>(); ... Iterator<String> itr = set.iterator(); ... returns the next element from the collection (throws a NoSuchElementException if there are none left to examine) next() removes the last value returned by next() (throws an IllegalStateException if you haven't called next() yet) remove() returns true if there are more elements to examine hasNext()
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
6 Iterator example Set<Integer> scores = new TreeSet<Integer>(); scores.add(94); scores.add(38); // Jenny scores.add(87); scores.add(43); // Marty scores.add(72); ... Iterator<Integer> itr = scores.iterator();
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 20

16-iterator-grammar - CSE 143 Lecture 16 Iterators;...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online