Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY.

Similar presentations


Presentation on theme: "COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY."— Presentation transcript:

1 COMP 103 Iterators and Iterable

2 RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY

3 Iterators Iterator iter = myTasks.iterator(); List myTasks = new ArrayList (); iter myTasks Conforms to the interface Iterator so… has methods hasNext() next() remove() Conforms to the interface List so… has methods add() remove() contains(), etc… 3

4  MyProgram cannot get inside a Collection object to do "for each...".  The Collection object has to go through its members, itself.  Has to be "Iterable" (i.e. can construct itself an Iterator object)  Each Collection class needs an associated Iterator class Why Iterators ? List MyProgram List mob; : for (Creature c : mob) { } Data Iterator next hasNext John Joleen JuliaJacobJane Justin Jack ANPDFCHEKJOMLWK 4

5  Operations on Iterators:  hasNext(): returns true iff there is another value to get  next() : returns the next value  remove(): rarely used  Standard pattern of use: Iterator itr = construct iterator while (itr.hasNext() ){ type var = itr.next(); … var … }  For each loop is convenient shorthand for this use: for (type var : Iterable ){ … var … Iterator Interface e.g. all Collection, since they extend Iterable 5

6 Making Collections Iterable 6 Collection size() add() etc Collection size() add() etc extends List All Collection methods + some own List All Collection methods + some own ArrayList implements all List methods implements Iterator hasNext() next() remove() Iterator hasNext() next() remove() Iterable extends public Iterator iterator() ArrayListIterator implements all Iterator methods implements ? + the ONE method of Iterable ArrayList : ArrayListIterator sits inside as a private inner class public Iterator iterator()

7 Example 7 public class ArrayBag implements “some Iterable type” { : public Iterator iterator(){ return new ArrayBagIterator (this); } : private class ArrayBagIterator implements Iterator { //constructor //define hasNext() method //define next() method //define remove method }//closing private inner class }//closing outer public class e.g. implements Bag OR extends some abstract class – later! e.g. implements Bag OR extends some abstract class – later!

8 [Aside: multiple classes in a file ]  Only one public class per file  Name of public class must be same as the file name.  Additional classes in the same file, after public class  Must not be public, or private  Can be called by the public class, or each other  Cannot be called from the command line (no “main” method)  This style wraps a whole program into a single file, but makes it less reusable.  Can have additional classes inside other classes  May be private – accessible only by enclosing class  May be public – generally accessible  Appropriate when inner class is strongly connected to enclosing class (as with an iterator for example)  Can also have anonymous inner classes inside methods! 8

9 Example  We have to be able to iterate over a Collection. How ?  Collection should implement the Iterable interface!  then any implementation of Collection will have to provide an "iterator()" method, which returns an iterator object (!) specific to that implementation.  this iterator should implement the Iterator interface  it must have two methods: hasNext(), next(), and remove()  the Collections interfaces (List, Queue...) are Iterable, so the Collections classes (ArrayList, LinkedList...) implement iterator(), which returns an Iterator object. 9 QUICK TIP: Map does not implement Iterable! You can iterate over Map via the three “collection views”: SET of keys, COLLECTION of values, SET of Map.Entry (key-value pairs)

10 Creating Iterators  Iterators are not just for Collection objects:  Anything that can generate a sequence of values  Scanner  Pseudo Random Number generator : public class RandNumIter implements Iterator { private int num = 1, public boolean hasNext(){ return true; // there is always another one! } public Integer next(){ num = (num * 92863) % 104729 + 1; return num; } public void remove(){throw new UnsupportedOperationException();} } Iterator randNums = new RandNumIter(); for (int i = 1; i<1000; i++) UI.print(randNums.next()+ "\n"); remove() is an optional method: must be defined, but doesn’t need to do anything! 10

11 Creating an Iterable (independent of collections)  Iterables are not just for Collection types  An Iterable is an object that provides an Iterator :  eg: An ArithSequence representing an infinite arithmetic sequence of numbers, with a starting number and a step size, eg 6, 9, 12, 15, 18,…. public class ArithSequence implements Iterable { private int start; private int step; public ArithSequence(int start, int step) { this.start = start; this.step = step; } : : public Iterator iterator() { return new ArithSequenceIterator(this); } constructor, just sets the first value and the step size "this" is needed, if using same name make an iterator 11

12 An Iterator, for an Iterable : //continued private class ArithSequenceIterator implements Iterator { private int nextNum; private ArithSequence source; public ArithSequenceIterator(ArithSequence seq) { source = seq; nextNum = seq.start; } public boolean hasNext() { return true; // there is always another one } public Integer next() { int ans = nextNum; nextNum += source.step; return ans; } public void remove() {throw new UnsupportedOperationException();} } // end of ArithSequenceIterator class }// end of ArithSequence class 12 so this class is only accessible from inside ArithSequence!

13 Using the Iterable  Can use the iterable object in the foreach loop: for (int n : new ArithSequence(15, 8)){ System.out.printf(“next number is %d \n”, n); }  Can use the iterator of the iterable object directly. ArithSequence seq = new ArithSequence(15, 8); Iterator iter = seq.iterator(); processFirstPage(iter); for (int p=2; p<maxPages; p++) processNextPage(p, iter); Notice you can pass iterator to different methods to deal with: ⇒ can “spread out” a for loop Constructs a multi page table of the sequence. The process … Page methods continue the sequence from the previous page 13

14 Working with Collections  Done: Declaring and Creating collections Using collections: adding, removing, getting, setting, putting,…. Iterating through collections [ Iterators, Iterable, and the "for each" loop ]  What next ?  Comparable and Comparator for Sorting Collections  Implementing Collection classes 14


Download ppt "COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY."

Similar presentations


Ads by Google