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

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
COMP 103 Linked Stack and Linked Queue.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
1 ADTs, Collection, Iterable/Iterator Interfaces Collections and the Java Collections API The Collection Interface and its Hierarchy The Iterable and Iterator.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Java's Collection Framework
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
COMP T2 Lecture 5 School of Engineering and Computer Science, Victoria University of Wellington Thomas Kuehne Maps, Stacks  Thomas Kuehne, Marcus.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
LinkedList Many slides from Horstmann modified by Dr V.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
1 Interfaces in Java’s Collection Framework Rick Mercer.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
List Interface and Linked List Mrs. Furman March 25, 2010.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Iteration Abstraction SWE Software Construction Fall 2009.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Collections Dwight Deugo Nesa Matic
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
COMP 103 Maps and Queues. RECAP  Iterators (for-each loop)  Bag, Sets, and Stacks - a class, not interface TODAY  Maps and Queues 2 RECAP-TODAY QUICK.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Using the Java Collection Libraries COMP 103 # T2
EECE 310: Software Engineering
Some Collections: BAGS, SETS, and STACKS
ADT’s, Collections/Generics and Iterators
JAVA COLLECTIONS LIBRARY
Iteration Abstraction
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Iteration Abstraction
JCF Collection classes and interfaces
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

COMP 103 Iterators and Iterable

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

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

 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

 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

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()

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!

[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

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)

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) % ; 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

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

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!

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

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