Public class numbersequence implements

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: er generator : public class NumCreator implements Iterator<Integer>{ private int num = 1, public boolean hasNext(){ return true; } public Integer next(){ num = (num * 92863) % 104729 + 1; return return num; } : Iterator<Integer> lottery = new NumCreator(); new for (int i = 1; i<1000; i++) textArea.append( "\n"); 16 Creating an Iterable • Class that provides an Iterator: • eg: A NumberSequence representing an infinite arithmetic sequence of numbers, with a starting number and a step size, eg 5, 8, 11, 14, 17,…. public class NumberSequence implements Iterable<Integer>{ private int start; private int step; public NumberSequence(int start, int step){ this.start = start; this.step = step; } public Iterator<Integer> iterator(){ return new NumberSequenceIterator(this); } 17 Creating an Iterator for an Iterable private class NumberSequenceIterator implements Iterator<Integer>{ private int nextNum; private NumberSequence source; public NumberSequenceIterator(NumberSequence ns){ source = ns; nextNum = ns.start; } public boolean hasNext(){ return return true; } public Integer next(){ int ans = nextNum; nextNum += ns.step; return ans; } } // end of NumberSequenceIterator class } // end of Number Sequence class 18 Using the Iterable • Can use the iterable object in the for each loop: for new for (int n : new NumberSequence(15, 8)){ System.out.printf(“next number is %d \n“, n); } • Can use the iterator of the iterable object directly. Iterator<Integer> iter = new NumberSequence(15, 8).iterator(); new processFirstPage(iter); for (int p=2; p<maxPages; p++) processNextPage(p, iter); (passing iterator to different methods to deal with) 19 Q&A • Java has specified a “Queue” interface. (T or F) • Java does not have any class support for “Priority Queue”. (T or F) • peek() operation under the Queue interface will throw an exception if the queue is empty. (T or F) • poll() operation under the Queue interface will throw an exception if the queue is empty. (T or F) • There is an element() method under the Queue interface. (T or F) • Iterable is an interface specification for a class that is equipped with an Iterator. • Iterator is an interface specification for a class that can generate iterative elements. 20 Summary • Queues and Priority Queues • Classes/Interfaces that accompany collections • Iterator • Iterable 21 Readings • [Mar07] Read 3.7, 3.4 22...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online