Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
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.
While Revisited u The while construct is (probably) the most frequently used iteration construct. u From the examples of it’s use we can see that it has.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Factory Design Pattern, cont’d COMP 401 Fall 2014 Lecture 13 10/2/2014.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Iterator COMP 401, Spring 2013 Lecture 07 1/31/2013.
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.
CS2110: SW Development Methods
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Linked Lists. RHS – SOC 2 Linked lists We can already store collec- tions of objects in arrays and array lists – why would we need other data structures…?
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Object Composition Interfaces Collections Covariance Object class Programming using C# LECTURE 10.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
Chapter 18 Java Collections Framework
1/20/03A2-1 CS494 Interfaces and Collection in Java.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
Encapsulation COMP 401, Fall 2014 Lecture 06 9/4/2014.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Software Development
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
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.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
What is Iterator Category: Behavioral Generic Way to Traverse Collection Not Related to Collection Implementation Details Not Related to the direction/fashion.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Written by: Dr. JJ Shepherd
Iteration Abstraction SWE Software Construction Fall 2009.
Using Sequential Containers Lecture 8 Hartmut Kaiser
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Observer / Observable COMP 401 Fall 2014 Lecture 14 10/7/2014.
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.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Collections Dwight Deugo Nesa Matic
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Functional Processing of Collections (Advanced) 6.0.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Data Abstraction: The Walls
Template Method Pattern Iterator Pattern
Functional Processing of Collections (Advanced)
Interator and Iterable
Presentation transcript:

Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014

Layers of Abstraction Simple objects – Object state (i.e., fields) are basic data types As objects become more complex… – Encapsulated object state is complex enough to require additional “layers of abstraction”. – Object state is modeled by a combination of other objects. – Recall early examples with Triangle and Point Lecture 5, ta.v09 and ta.v10

Composition and Aggregation Two design techniques for creating an object that encapsulates other objects. – Whole / part relationship – Any specific situation is not necessarily strictly one or the other. In a nutshull… – Composition The individual parts that make up the whole are “owned” solely by the whole. – They don’t otherwise have a reason for being. – Aggregation The individual parts that make up the whole may also exist on their own outside of the whole. – Or even as a part of other objects.

Example of Aggregation lec10.ex1 – Course Models a course at the university Encapsulates Room, Professor, and a list of Student objects

Characteristics of Aggregation Encapsulated objects provided externally – As parameters to constructor – Getters and setters for these components often provided. Encapsulated objects may be independently referenced outside of the aggregating object – Including possibly as part of another aggregation.

Example of Composition lec10.ex2 – Car Two implementations: HondaOdyssey and Porche911 Both encapsulate an implementation of Horn and an implementation of Engine – Implementations of Engine written with inheritance. EngineImpl provides most of the implementation – Abstract class ManualEngine and AutomaticEngine are subclasses – Override setGear()

Characteristics of Composition Encapsulated objects created internally – Usually within the constructor – No setters and often no getters Encapsulated objects do not make sense outside of the abstraction. – Not shared with other abstractions Functionality / state of encapsulated objects only accessible through the abstraction

Delegation Claiming an “is-a” relationship with an interface but relying on another object to actually do the work. Can occur with either aggregation or composition. – Although more common with composition Composition example revisited – lec10.ex3 – Both Car implementations also now claim Horn and/or AdjustableHorn interfaces as well. Actual work of these interfaces delegated to internal horn object.

Part 2: Iterator

Design Situation Suppose we have an object that encapsulates some sort of collection. – SongLibrary A collection of songs in an iTunes-like system – PolygonModel A collection of polygons in a 3D modeling system

Design Situation Now suppose we have code outside of this collection object that needs to examine each element of the underlying collection in turn. – SongFilter A object that represents a search criteria to be applied to a collection of songs – An intersection test in which each polygon of a PolygonModel needs to be evaluated

Strategy 1: Provide access to underlying collection as an array. SongLibrary – public Song[] getSongs() PolygonModel – public Polygon[] getPolygons() Drawbacks? – May have to do a lot of work to create the array – Collection may be result of generative process There may be no “end” to the collection. Or the collection may be large so we don’t want to provide the whole thing at once.

Strategy 2: Provide index access to each underlying item in collection SongLibrary – public int getNumSongs(); – public Song getSong(int song_idx); PolygonModel – public int getNumPolygons(); – public Polygon getPolygon(int polygon_idx); Drawbacks? – Doesn’t help with generative collections – Imposes restrictions on how collection is represented and linearized – Deteriorates encapsulation

Strategy 3: Internalize a “cursor” SongLibrary – public void resetSongCursor(); – public Song getNextSong(); – public boolean isCursorAtEnd(); Drawbacks? – Can’t have two traversals going at the same time. – But, this does come close.

Iterator Design Pattern “Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation” – Gang of Four, Design Patterns Consider: for(int i=0; i<slist.size(); i++) { Song next_song = slist.get(i); // Do something with next_song. }

Iterator Design Pattern Iterator object encapsulates details of item traversal. – Understands details of the underlying collection. – Manages order of items May want a traversal that is not just first to last. Underlying collection may not have a natural linear order. – Manages state of traversal Allows traversal to be picked up again later. Assumption: underlying collection is not changed or modified while the traversal is occurring. – Iterator should be able to detect this and signal an error – Variant of pattern will have iterator provide methods that modify underlying collection safely

Components of Iterator Pattern Collection object is “iterable” – Provides a method that returns an object that acts as an iterator. Iterator object provides access to the elements in turn. – At the very least: A method to test whether more items exist. A method to retrieve the next item. – Other possible features: Methods that remove an item safely. Method to “peek” at the next item. Method to reset the traversal.

Java Iterator Pattern Interfaces The Java Collections Framework defines two generic interfaces for supporting the iterable design pattern – Implemented by the various collection types such as List, Map, Set, etc. Iterable – Interator iterator() Iterator

boolean hasNext() – Are we at the end of the traversal? E next() – Get the next item of the traversal. – Throws a runtime exception if no next item. void remove() – Not supported by all implementations. – Safely removes last item retrieved by next() from the underlying collection.

Iterable examples lec10.ex4 – Main1 Simple use – Main2 Parallel iterators – Main3 Simultaneous iterators – Main4 for – each syntactic sugar

Main1 Visualized (1) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy

Main1 Visualized (2) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy Iterator iter 0 0 next_idx list

Main1 Visualized (3) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy Iterator iter 0 0 next_idx list public boolean hasNext() { if (next_idx < list.size()) { return true; } return false; } NOTE: This may or may not be how it is actually implemented, but it is effectively what is going on.

Main1 Visualized (4) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy Iterator iter 1 1 next_idx list public Song next() { Song s = list.get(next_idx); next_idx++; return s; } NOTE: Real implementation would first check to see if hasNext() is still true and throw an exception otherwise.

lec10.ex4.Main2 Parallel iteration – Processes two different lists Iterator associated with each. Iterators advance unevenly

lec10.ex4.Main3 Simultaneous iteration – 2 Iterators, 1 List Insert your own joke here.

for - each Java provides “syntactic sugar” for a particularly common use of iterators. – for-each loop – Supposing e_coll is Iterable, then these are equivalent: Iterator iter = e_coll.iterator(); while (iter.hasNext()) { E elem = iter.next(); // Do something with element } for (E elem : e_coll) { // Do something with elem } lec10.ex4.Main4

for-each with Array The for-each construct also works with Arrays Useful if you need to process the elements of an array but do not need the index. String[] names = new String[] {“Amy”, “Mike”, “Cameron”, “Claire”}; for (String n : names) { System.out.println(n); }

lec10.ex5 A more complicated iterator – Can build iterators that do things other than just go through every item. Prior examples made use of Iterator built into List, here we are going to implement our own specialized version of Iterator