Containers CMPS 2143. Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Singly linked lists Doubly linked lists
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Chapter 12 Lists and Iterators. List Its an abstract concept not a vector, array, or linked structure. Those are implementations of a List. A list is a.
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.
Java Review Interface, Casting, Generics, Iterator.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Generic programming in Java
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
Inheritance1 Inheritance Software re-use with derived classes.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
1 Introduction to CS Agenda Syllabus Schedule Lecture: the management of complexity.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
Object Oriented Data Structures
Chapter 11 and 12: Abstract Data Types and Encapsulation Constructs; Support for Object Orientation Lesson 11.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Information and Computer Sciences University of Hawaii, Manoa
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
CSSE501 Object-Oriented Development. Chapter 11: Static and Dynamic Behavior  In this chapter we will examine the differences between static and dynamic.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Genericity Ranga Rodrigo Based on Mark Priestley's Lectures.
Object Oriented Programming Lecture 11: Polymorphism.
More on Polymorphism. Ever have one of those days?
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Types in programming languages1 What are types, and why do we need them?
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Session 18 Chapter 8: Understanding Inheritance. Recall Exercise 2 From Tuesday It’s very annoying to move a target from the pallet and drop it in the.
3C-1 Purity Typing Language semantics Inheritance model  Single vs. Multiple inheritance  Common root Modular mechanisms Generics Object Oriented Languages.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 6. Dictionaries(3): Binary Search Trees.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Polymorphic Variables CMPS2143. The Polymorphic Variable A polymorphic variable is a variable that can reference more than one type of object (that is,
Modern Programming Tools And Techniques-I
Sixth Lecture ArrayList Abstract Class and Interface
Week 15 – Monday CS221.
CSC 143 Queues [Chapter 7].
Generic programming in Java
CMSC 202 Generics.
SPL – PS1 Introduction to C++.
Presentation transcript:

Containers CMPS 2143

Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary trees, sets, dictionaries, etc. So common expect ideal for development as reusable components

Containers in dynamically typed languages: Easier in dynamically typed languages to produce reusable containers Often those languages have them built-in Easier because value retains knowledge of its type (self referential) Also dynamic languages permit values of different classes heterogeneous collections

Look at several collections abstract Collection can add, remove, get size, check if empty, … Set - inherits/overrides/adds Collection methods a set is an unordered Collection of unique elements Dictionary – inherits/overrides/adds methods a dictionary is a Set where each element of the set is an Association representing a single key/value pair Bag – inherits/overrides/adds Collection methods a bag is similar to a set, but values do not have to be unique Bag will also use composition

inheritance as mechanism for specialization (Set and Bag) deferred methods (add and remove in Collection) inheritance as mechanism for construction (Dictionary)

composition (Bag has a dictionary) key is the element in the bag value is the number of times element is in the bag

Containers in Statically Typed Languages Static typing can interfere with software reuse 3 solutions 1.Use principle of substitution to store values in a container and combine with down casting (reverse polymorphism) when values removed from container 2.Use principle of substitution but avoid down casting through use of overriding 3.Use generics or templates

class List { public: //methods void insert (int newVal); private: class Node { //Node is an inner class public: // inside class List int value; // so okay for public data Node * next; }; … Node * head; }; C++ Linked list of integers

Concerns Question of reusability suppose we now want a list of doubles Problem: conventional static languages are too strongly typed int data type is intrinsic part of definition But OOP languages can utilize principle of substitution and generics

Substitution and downcasting class List { public: //methods void insert (Object newVal); Object removeAt (int index); private: class Node {//inner class public: Object value; Node * next; }; … Node * head; };

Substitution and downcasting List catList; Cat aCat (Leo); Dog aDog (Fido); catList.insert(aCat); Cat bCat = (Cat) catList.removeAt (1); //downcasting from //Object to Cat catList.insert(aDog); //aDog is an Object, no compiler error Cat bCat = (Cat) catList.removeAt (1); //OOPS! NOW error!

Notes: Can only have heterogenous collections if there is a super Object in the language (as in Java). Even so cannot include primitive types (int, double, char, … do not inherit from Object) solution is to have a wrapper class class Double to hold a double value with get/set methods Java has some built-in

Using substitution and overriding A cast expression is often considered to be NOT truly object-oriented Can avoid with use of substitution combined with method overriding only possible if original developer knows how an object will be used (even if they dont know the type of value stored in container) Used in a few restricted situations

C#, Java example Events handled by Listener objects that are attached to a container like a Window object. When event occurs in a given window, all registered listeners are notified mouse movement, mouse pressed, key pressed, text box changed, etc. Java also provides adapters that implement interfaces Programmer defines a class to implement interface and overrides the methods they want

Parameterized classes using principle of substitution in previous 2 techniques is only suitable if there is a parent class that can be used as basis if a language does not have a single root that is ancestor to all classes, then… use generics.

Templates #pragma once template class List { public: //methods void insert (ItemType newVal); ItemType removeAt (int index); private: class Node { public: ItemType value; Node * next; }; … Node * head; }; #include List.cpp

Templates To use List intList; List doubleList; In this way, homogeneous lists can be created Book says you cant have heterogeneous lists, but as long as you use references… List shapeList;

Element traversal on Containers Provides method that allow you to loop over the elements in the container bool hasMoreElements(); //return true iff there are more elements to process ItemType nextElement(); //return next element void reset(); //start at first element

Iterator methods template class List { public: void insert (ItemType newVal); ItemType removeAt (int index); void resetCursor(); void advanceCursor(); bool cursorAtEnd(); ItemType nextElement (); private: class Node { public: ItemType value; Node * next; }; … Node * head; Node * cursor; //for iteration };

#include List.h #include using namespace std; void List:: resetCursor(){cursor = head;} void List:: advanceCursor() { if (cursor != null) cursor = cursor->next; else cout << Error: Cannot advance cursor, cursor at end \n; } bool List:: cursorAtEnd(){return cursor == null}; ItemType List:: nextElement (){ if (cursor != null) return cursor->value; else cout << Error: Cannot advance cursor, cursor at end \n; }

#include List.h #include using namespace std; template void loadList (List & list); template void sumList(List & list, ItemType & sum); void main() { List intList; int sum = 0; loadList (intList); sumList (intList, sum); cout << Sum of items in list is << sum << endl; system(pause); }

template void loadList (List & list) { list.insert(1); list.insert(2); list.insert(5); } template void sumList(List & list, ItemType & sum) { list.resetCursor(); while (!list.cursorAtEnd()) { i = list.nextElement(); sum += I; list.advanceCursor(); }

#include List.h #include ComplexNumber.h #include using namespace std; template void loadList (List & list); template void sumList(List & list, ItemType & sum); void main() { List intList; ComplexNumber sum; //default constructor sets sum = 0+0i loadList (intList); sumList (intList, sum); cout << Sum of items in list is << sum << endl; system(pause); }

Visual Studio STL containers us/library/1fe2x6kt(v=vs.110).aspx us/library/1fe2x6kt(v=vs.110).aspx

Study pg. 387: 1, 3, 5