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.

Slides:



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

DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
CS18000: Problem Solving and Object-Oriented Programming.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
OOP in Java – Inner Classes Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes).
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Grouping Objects 3 Iterators, collections and the while loop.
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CS 280 Data Structures Professor John Peterson. Project 9 Questions? IS280.
1 Topic 8 Iterators "First things first, but not necessarily in that order " -Dr. Who.
1 Implementing a queue in an array Hashing We show a neat idea that allows a queue to be stored in an array but takes constant time for both adding and.
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
CS2110 Recitation Week 8. Hashing Hashing: An implementation of a set. It provides O(1) expected time for set operations Set operations Make the set empty.
Problem Of The Day  Decipher the following phrase: STANDS 0 _
08 1 Abstract Data Types Problem Sets: PS2 due due Monday, Feburary 26 PS3 due Wednesday, March 7 Wellesley College CS230 Lecture 08 Monday, February 26.
1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section 12.3.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
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.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
Effective Java: Generics Last Updated: Spring 2009.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CSC 205 Programming II Lecture 18 The Eight Queens Problem.
CMSC 341 Linked Lists, Stacks and Queues. 8/3/2007 UMBC CMSC 341 LSQ 2 Implementing Your Own Linked List To create a doubly linked list as seen below.
1 Iterators "First things first, but not necessarily in that order " -Dr. Who CS Computer Science II.
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.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Java Implementation: Part 4 Software Construction Lecture 9.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
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.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Generics with ArrayList and HashSet 1 ge·ner·ic adjective \jə ̇ˈ nerik, -rēk\ relating or applied to or descriptive of all members of a genus, species,
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Iteration Abstraction SWE Software Construction Fall 2009.
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.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
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.
Vector program patterns Vectors contain many elements, so loops are common. Counted processing // Print the first 3 elements. for (int i = 0; i < 3; i++)
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Building Java Programs Generics, hashing reading: 18.1.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
CS2005 Week 7 Lectures Set Abstract Data Type.
Iterators.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 15: More Iterators
Iteration Abstraction
"First things first, but not necessarily in that order " -Dr. Who
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Iteration Abstraction
Software Design Lecture : 39.
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

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 collection of elements (duplicates allowed) set: bag in which no duplicated allowed (call it a unibag!) list: ordered collection of elements 1 We show you how to fix class C so that you can write: C ob= new C (); Populate ob with some elements; for (String s: ob) { do something with s } foreach loop

Interface Iterator Start with interface Iterator. A class that implements Iterator needs three functions that make it easy to “enumerate” the elements of a collection —a bag, a set, a list, whatever. Required functions: hasNext() next() remove() 2 in java.util To enumerate: to provide a list of

To implement interface Iterator in java.util interface Iterator { /** Return true iff the enumeration has more elements */ public boolean hasNext(); /** Return the next element of the enumeration. Throw a NoSuchElementException if there are no more. */ public T next(); /** Remove the last element returned by the iterator. … Throw UnsupportedOperationException if you don’t want to implement this operation. We don’t. */ public void remove(); } 3

Example of a class that implements Iterator Recall implementation of hashing from last week. Each element of b is either 1.null 2.A HashEntry object with isInSet false 3.A HashEntry object with isInSet true 4 We need a class that enumerates the elements in the objects in alternative 3. b "abc" "235" "aaa" "1$2" "xy"

Class HashSetIterator /** An instance is an Iterator of this HashSet */ private class HashSetIterator implements Iterator { // all elements in b[0..pos] have been enumerated private int pos= -1; // number of elements that have been enumerated private int enumerated= 0; /** = "there is another element to enumerate". */ boolean hasNext() { return enumerated != size; } // continued on next slide field size of class HashSet

/** = the next element to enumerate. Throw a NoSuchElementException if no elements left */ T next() { if (!hasNext()) throw new NoSuchElementException(); pos= pos+1; while (b[pos] == null || !b[pos].isInSet) { pos= pos+1; } enumerated= enumerated+1; return b[pos].element; } /** Remove is not supported. */ void remove() throws …{ throw new UnsupportedOperationException(); } Class HashSetIterator

HashSetIterator has to be an inner class public class HashSet { private HashEntry [] b; private int size= 0; public boolean add(T x) { …} … private class HashSetIterator implements Iterator { public boolean hasNext() { … } public T next() { … } public void remove() { … } } 7 These refer to size and b It has to be defined inside class HashSet These refer to type T

Using the iterator public class HashSet { … public Iterator iterator( ) { return new HashSetIterator(); } private class HashSetIterator implements Iterator {…} } 8 HashSet hs= new HashSet (); Add a bunch of integers to hs; // Print all elements in hs Iterator it= hs.iterator(); while (it.hasNext()) { Integer k= it.next(); System.out.println(k); }

Using the iterator public class HashSet { public boolean add(T x) … Iterator iterator( ) private class HashSetIterator implements Iterator } 9 HashSet hs= new HashSet (); Add a bunch of integers to hs; // Print all elements in hs while (it.hasNext()) { Integer k= it.next(); System.out.println(k); } hs … add(…) iterator() HashSetIterator Iterator it= hs.iterator(); it hasNext() {…} next() {…} b..

Interface Iterable In java.lang Requires one method: /** Return an Iterator over a set of elements of type T */ public Iterator iterator() 10 Java API says “set”, but should say “collection” –a set, a bag, a list, whatever If class C implements Iterable, we can write for (T v : object) {…}

public class HashSet { private HashEntry [] b; private int size= 0; public boolean add(T x) { …} … private class HashSetIterator implements Iterator { public boolean hasNext() { … } public T next() { … } public void remove() { … } } 11 implements Iterable /** Return an Iterator for enumerating the set. */ Iterator iterator( ) { return new HashSetIterator(); }

Using the foreach loop public class HashSet implements Iterable { Iterator iterator( ) private class HashSetIterator implements Iterator … 12 HashSet hs= new HashSet (); Add a bunch of strings to hs; // Print all elements in hs Iterator it= hs.iterator(); while (it.hasNext()) { Integer k= it.next(); System.out.println(k); } for (Integer k : hs) { System.out.println(k); } HashSet implements Iterable, so you can replace the declaration of it and the while loop by the foreach loop. “syntactic sugar”

Don’t try to change the set in a foreach!! 13 HashSet hs= new HashSet (); Add a bunch of strings to hs; // Print all elements in hs for (Integer k : hs) { hs.add(-k); } This may change array b and int field size. May cause rehash. hs’s class invariant (meanings of hs.pos and it.enumerated) no longer holds. Iterator it= hs.iterator(); while (it.hasNext()) { Integer k= it.next(); hs.add(-k); } Don’t do this either 

HashSetIterator is an inner class of HashSet public class HashSet implements Iterable { public boolean add(T x) … Iterator iterator( ) private class HashSetIterator implements iterator } 14 hs … add(…) iterator() HashSetIterator Declared within HashSet, often made private so can’t be referenced directly from outside size 20 b HashSetIterator is in each HashSet object

Think of HashSetIterator objects also as being inside a HashSet object. Then, normal inside-out rule shows you that hasNext() and next() can reference b and size. 15 HashSet hs= new HashSet (); … Iterator it1= hs.iterator(); Iterator it2= hs.iterator(); hs … add(…) iterator() HashSetIterator it1 hasNext() {…} next() {…} hasNext() {…} next() {…} it2 size 20 b Diagram: two HashSetIterator objects in HashSet object. Two enumerations of set going on at same time?

A foreach loop within a foreach loop public class HashSet implements Iterable ; Iterator iterator( ) private class HashSetIterator implements Iterator } 16 HashSet hs= new HashSet (); Add a bunch of strings to hs; for (Integer k : hs) { for (Integer h : hs) { Compare set elements k and h in some way }

Nested class Inner class static nested class public class HashSet implements Iterable ; public boolean add(T x) … Iterator iterator( ) private class HashSetIterator implements Iterator {} private static class HashEntry {} } 17 Nested class: a class declared inside another: HashSetIterator and HashEntry are declared within class HashSet, so they are nested classes.

Nested class Inner class static nested class public class HashSet implements Iterable ; public boolean add(T x) … Iterator iterator( ) private class HashSetIterator implements Iterator {} private static class HashEntry {} } 18 Inner class: a nested class that is not static. When instances are created, they live within an object of the outer class. HashSetIterator is an inner class. It has to live within a HashSet object so that its objects can reference fields b and size. See slide 15!

Nested class Static nested class Inner class public class HashSet implements Iterable ; public boolean add(T x) … Iterator iterator( ) private class HashSetIterator implements Iterator {} private static class HashEntry {} } 19 Static nested class: a nested class that is static. When instances are created, they do not live within an object of the outer class. HashEntry is a static nested class. Its objects do not need to be in HashSet objects because it does not reference HashSet fields or instance methods.

Nested class Inner class static nested class 20 Make a class an inner class so that its objects can reference fields or instance methods of the outer class. Make a class SNC a static nested class within class C when: 1.SNC is used only within C and there is no need for program parts outside C to know about SNC. Example: HashEntry 2.SNC does not reference any fields or instance methods of C. Example: HashEntry Effect: Nesting SNC within C hides it from the outside world. Only those interested in how C is implemented need to know about it. Making SNC static is more efficient —there is only one copy of the class; it does not reside in objects of class C.

Nested class Inner class static nested class 21 There are certain restrictions on inner classes and nested static classes. We don’t go into them. You have seen one nested static class: HashEntry You have seen several inner classes: HashSetIterator and some classes that are used to help implement listening to GUI events –discussed in that lecture.