11 each iteration and for each loop standard for each

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: d return value at front/head of queue or null if the queue is empty • (sometimes called “dequeue”, like “pop”) • peek ⇒ value peek() • return value at head of queue, or null if queue is empty (doesn’t remove from queue) • remove and element remove() element() • like poll() and peek(), but throw exception if queue is empty. 11 each” Iteration and “for each” loop • Standard “for each” loop with collections: for (Face face : crowd) { face.render(canvas); } for (Map.Entry<String,Integer> entry : phonebook.entrySet()){ textArea.append(entry.getKey()+" : "+entry.getValue()); } • Uses Iterators. “Sharon” ⇒ 5978 “Stuart” ⇒ 6730 “Lindsay” ⇒ 5656 “John” ⇒ 5670 “Pondy” ⇒ 5834 12 Iterators? Why Iterators? • Program cannot get inside the Collection object Jack • The Collection constructs an Iterator Jane Jacob Julia AN PD F CHE K J OMLWK Justin Joleen John Program List<Face> crowd; : hasNext Iterator<Face> List <Face> next Data for (Face f : crowd){ } • Iterator may access inside of collection • Iterator provides elements one at a time. • Each Collection class needs an associated Iterator class 13 Iterator Interface • Operations on Iterators: • hasNext hasNext() : returns true iff there is another value to get • next() : returns the next value next • Standard pattern of use: Iterator<type > itr = construct iterator while (itr.hasNext() ){ type var = itr.next(); … var … } • Almost same as the “for each” loop: for (type var : collection ){ … var … 14 Iterators and Iterable • But, the “for each” loop requires an Iterable: each” for (type var : Iterable <type> ){ … var … } Iterable <T> eg, all Collections Iterator <T> public Iterator<T> iterator(); public boolean hasNext(); public T next(); Iterator<type > itr = construct iterator while (itr.hasNext() ){ type var = itr.next(); … var … } 15 Creating Iterators • Iterators are not just for Collection objects: • Anything that should generate a sequence of values • Scanner • Pseudo Random Numb...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online