1 Genericity Parameterizing by Type. 2 Generic Class One that is parameterized by type  Works when feature semantics is common to a set of types On object.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
C++ Programming Languages
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Generic programming in Java
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chair of Software Engineering OOSC - Summer Semester Object-Oriented Software Construction Bertrand Meyer Lecture 6: Genericity.
1 CS Generics L. Grewe 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Chair of Software Engineering ATOT - Lecture 7, 23 April Advanced Topics in Object Technology Bertrand Meyer.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
Building Java Programs
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
OOP Languages: Java vs C++
Object Oriented Data Structures
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Chapter 3 Introduction to Collections – Stacks Modified
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Effective Java: Generics Last Updated: Spring 2009.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
CSC 212 Stacks & Queues. Announcement Many programs not compiled before submission  Several could not be compiled  Several others not tested with javadoc.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Chapter 4 Data Structures ADT Examples  Stack  Queue  Trees.
Genericity Ranga Rodrigo Based on Mark Priestley's Lectures.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
CMSC 330: Organization of Programming Languages Java Generics.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
CS 2430 Day 24. Announcements Quiz this Friday Program 5 posted on Monday Program 4 due date: Friday at 10pm Program 4 grace date: Wednesday at 10pm (don’t.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Click to edit Master text styles Stacks Data Structure.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Stacks.
COP 3503 FALL 2012 Shayan Javed Lecture 8
Generics, Lambdas, Reflections
Corresponds with Chapter 5
A type is a collection of values
Presentation transcript:

1 Genericity Parameterizing by Type

2 Generic Class One that is parameterized by type  Works when feature semantics is common to a set of types On object declaration the parameter is assigned a type  For example catalogue : ARRAY [ PERSON ]  We want an array of references to persons  All the array operations for catalogue are customized to use persons

3 Common Generic Classes Collection classes – classes that are collections of objects  Strong typing requires specifying a type  But feature semantics is independent of type Examples  Sets, Stacks, Arrays, Queues, Sequences a : ARRAY [ MATRIX_ELEMENT ] a : ARRAY [ INTEGER ] a : ARRAY [ STACK [ ELEPHANTS ] ]

4 Your Generic Classes You can write generic classes Why is this useful?  reuse  reliability

5 Understanding Genericity We need  lists of INTEGER, lists of BOOK, lists of STRING etc. Without genericity we have  INTEGER_LIST, BOOK_LIST, STRING_LIST Problem — Reusability.  The basic operations (e.g. extend)are essentially the same.  Have to re-write essentially the same code over and over again.  Violation of the Single Choice Principle — changing STACK requires multiple changes, instead of a change at a single point.

6 Generic Stack class STACK [ G ] feature count : INTEGER -- number of elements empty : BOOLEAN is do... end full : BOOLEAN is do... end item : G is do... end put ( x : G ) is do... end remove is do... end end -- STACK Can use parameter G wherever a type is expected

7 Generic Array class ARRAY [ P ] creation make feature make ( minIndex, maxIndex : INTEGER ) is do... end lower, upper, count : INTEGER put ( value : P ; index : INTEGER ) is do... end infix item ( index : INTEGER ) : P is do... end end -- ARRAY

8 Using the Generic Array circus : ARRAY [ STACK [ ELEPHANTS ] ] create circus.make ( 1, 200 ) st_el : STACK [ ELEPHANTS ] -- element to put in the array create st_el circus.put ( st_el, 30 ) -- put an element into the array st_el2 : STACK [ ELEPHANTS ] st_el2 := get an element from the array

9 Types of Genericity Types  Unconstrained  Constrained The previous examples showed unconstrained genericity  Any type could be passed as a parameter

10 Constrained Genericity Used when the generic type parameters must satisfy some conditions The following makes sense only if P has the feature ≥ class VECTOR [ P ] feature... minimum ( x, y : P ) : P is do if x ≥ y then Result := y else Result := x end... end How we enforce constraints is discussed in Inheritance Techniques

11 Discussion on Genericity What programming languages offer genericity that you know of? Java? C++? Other? C++ has the template: Set s ; Java has no genericity – can it be faked? What is the effect of genericity on  compile time  size of the generated code  execution time  execution space Warning: generics cheap in Eiffel – expensive in C++

12 Java Stack public class Stack { private int count; private int capacity; private int capacityIncrement; private Object[] itemArray; // instead of ARRAY[G] Stack() {//constructor limited to class name count= 0; capacity= 10; capacityIncrement= 5; itemArray= new Object[capacity]; // no pre/postconditions/invariants } public boolean empty() { return (count == 0); }

13 Java Stack (cont.) public void push(Object x) { if(count == capacity) { capacity += capacityIncrement; Object[] tempArray= new Object[capacity]; for(int i=0; i < count; i++) tempArray[i]= itemArray[i]; itemArray= tempArray; } itemArray[count++]= x; } public Object pop() { if(count == 0) // no preconditions; // hence defensive programming return null; else return itemArray[--count]; }

14 Java Stack (cont.) public Object peek() { if(count == 0) return null; else return itemArray[count-1]; } }// end Stack; no class invariant public class Point { public int x; public int y; }

15 Java Stack runtime error class testStack { public static void main(String[] args) { Stack s = new Stack(); Point upperRight = new Point(); upperRight.x= 1280;// breaks information hiding upperRight.y= 1024;// cannot guarantee any contract s.push("red"); s.push("green"); // push some String s.push("blue"); // objects on the stack s.push(upperRight);// push a POINT object on the stack while(!s.empty()) {// cast all items from OBJECT String color = (String) s.pop(); // to STRING in order to print System.out.println(color); }}} // causes a run-time error in Java // ClassCastException: Point at testStack.main(testStack.java:18) // In Eiffel it is a compile time error

16 Does run-time vs. compile time matter? Principle: When flying a plane, run-time is too late to find out that you don’t have landing gear! Always better to catch errors at compile time! This is the main purpose of Strong Typing [OOSC2, Chapter 17]. Genericity helps to enforce Strong Typing, i.e. no run- time typing errors  LIST[INTEGER]  LIST[BOOK]  LIST[STRING]