Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.

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

Fun with Lists for the Novice and Expert Scott Reed Brain Hz Software (760)
Collections Chapter Java Collection Frameworks The Java collection framework is a set of utility classes and interfaces. Designed for working with.
Data Structures and Collections
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Polymorphism. 3 Fundamental Properties of OO 1. Encapsulation 2. Polymorphism 3. Inheritance These are the 3 building blocks of object-oriented design.
1 Generic Collections Chapter Objectives You will be able to Use generic collection classes available in the.NET framework.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
New Features in C# 2.0 Sergey Baidachni MCT, MCSD, MCDBA.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
Reflection, Conversions, and Exceptions Tom Roeder CS fa.
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.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
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.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
16 - Generics. 2 NOEA2009Java-kursus – Generics ”Generic” Programming in C#/Java (as it was until Summer 2005) All classes inherit from Object So we can.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
Generics in.NET and C# Generics. ”Generic” Programming in C#/Java (as it was until Summer 2005) All classes inherit from Object So we can apply polymorphism.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
JAVA COURSE LESSON2 BY OMPUTER ENGINEEING ASSOCIATION.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
[ISRAR ALI] Hammad Khan. The namespace keyword is used to declare a scope. Making software components reusable can result in naming collisions (two classes.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Interface: (e.g. IDictionary) Specification class Appl{ ---- IDictionary dic; dic= new XXX(); application class: Dictionary SortedDictionary ----
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009.
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
Interfaces and Polymorphism CS 162 (Summer 2009).
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
1.Net programmingGenericsNOEA / 2009 Generics 11. Generics in.NET and C#
Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
Java Collection Classes Com379PT
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
1 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various © University of Linz, Institute for System.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
Sixth Lecture ArrayList Abstract Class and Interface
Advanced .NET Programming I 2nd Lecture
Generics A Brief Review 16-Nov-18.
ArrayLists 22-Feb-19.
Binding 10: Binding Programming C# © 2003 DevelopMentor, Inc.
Presentation transcript:

Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1

”Generic” Programming without generics in C# (as it was until Summer 2005 – and you still see it, also in other languages) All classes inherit from Object So we can apply polymorphism and use Object as static type for elements in containers For instance: Object[ ] data –this array may take any object as element –This approach is well known from standard collections as ArrayList, HashTable etc. FEN 2014UCN Teknologi/act2learn2

Pros and Cons Pros –heterogeneous collections –... Cons –many type casts –not type safe type checking is done runtime when casting –int and other native (value) type must be wrapped. (boxing – costs runtime overhead) Is this really an advantage? FEN 2014UCN Teknologi/act2learn3

The Idea: Types as Parameters C# before 2005: ArrayList al = new ArrayList(); Customer c= (Customer)al[i];//cast Instead we want something like: List al = new List (); Customer c= al[i]; – The compiler is able to check that only objects with static type Customer is placed in al – So the compiler knows that everything that may come out from al has static type Customer –So static type checking instead of dynamic type checking is possible –Dynamic casting can be avoided (but is not in all implementations) Type parameter FEN 2014UCN Teknologi/act2learn4 And that’s what we got

oldFashion: EmpSeqIteratorEmpSeqIterator Employee a1 = new Employee("Joe", "Programmer", 10000); Employee a = new Employee("Curt", "Senior Programmer", 20000); Employee b = new Employee("Carl", "Programmer", 10000); Employee c = new Employee("Karen", "System Programmer", 13000); Employee d = new Employee("Lisa", "Programmer", 11000); Employee e = new Employee("John", "System Engineer", 9000); string s = "HELLOOOO!"; ArrayList emps = new ArrayList(); emps.Add(a1); emps.Add(a); emps.Add(b); emps.Add(c); emps.Add(d); emps.Add(e); emps.Add(s); FEN 2014UCN Teknologi/act2learn5 for(int i = 0; i < emps.Count - 1; i++) Console.WriteLine(((Employee)emps[i]).Name); Console.WriteLine(); Explicit cast is necessary, but it works fine. No compiler error!

oldFashion: EmpSeqIteratorEmpSeqIterator Employee a1 = new Employee("Joe", "Programmer", 10000); Employee a = new Employee("Curt", "Senior Programmer", 20000); Employee b = new Employee("Carl", "Programmer", 10000); Employee c = new Employee("Karen", "System Programmer", 13000); Employee d = new Employee("Lisa", "Programmer", 11000); Employee e = new Employee("John", "System Engineer", 9000); string s = "HELLOOOO!"; ArrayList emps = new ArrayList(); emps.Add(a1); emps.Add(a); emps.Add(b); emps.Add(c); emps.Add(d); emps.Add(e); emps.Add(s); FEN 2014UCN Teknologi/act2learn6 foreach (Employee ans in emps) Console.WriteLine(ans.Name); Console.WriteLine(); Implicit cast No compiler error! Runtime exception at string

withGenerics: EmpSeqIteratorEmpSeqIterator Employee a1 = new Employee("Joe", "Programmer", 10000); Employee a = new Employee("Curt", "Senior Programmer", 20000); Employee b = new Employee("Carl", "Programmer", 10000); Employee c = new Employee("Karen", "System Programmer", 13000); Employee d = new Employee("Lisa", "Programmer", 11000); Employee e = new Employee("John", "System Engineer", 9000); string s = "HELLOOOO!"; IList emps = new List (); emps.Add(a1); emps.Add(a); emps.Add(b); emps.Add(c); emps.Add(d); emps.Add(e); emps.Add(s); //COMPILER ERROR!!!! FEN 2014UCN Teknologi/act2learn7

Do your own container homeMade: EmpSeqIteratorEmpSeqIterator Encapsulate all the casts: FEN 2014UCN Teknologi/act2learn8 interface ISeqEmps : IEnumerable { void insert(int i, Employee e); //Pre: 0 <= i <= length() //Post: e is insert at position i in the sequence // Succeeding elements are move to oldPos+1 Employee inspect(int i); //Pre: 0 <= i < length() //Post: the element at position i is returned void update(int i, Employee e); //--- IEnumerable GetReverseEnumerator(); We would like to have an iterator and use foreach We may want to create an iterator of our own

Do your own container homeMade: EmpSeqIteratorEmpSeqIterator Encapsulate all the casts: FEN 2014UCN Teknologi/act2learn9 class SeqEmps: ISeqEmps { private ArrayList l; public void insert(int i, Employee e){ l.Insert(i,e); } public Employee inspect(int i){ return (Employee)l[i]; } public IEnumerator GetEnumerator(){ return l.GetEnumerator(); } public IEnumerable GetReverseEnumerator(){ for (int i = l.Count; i > 0; i--) yield return l[i - 1]; } //--- } Return the ArrayList iterator Return our own iterator

Implementation of Generics “Macro-expansion” (C++ template): –Static checking, no casts, larger executables. Encapsulating the casts (like “homeMade”, Java): –Static checking, dynamic cast C#: –C++ way for value types –Java way for reference types FEN 2014UCN Teknologi/act2learn10

Do your own generic container: MyListProject MyListProject FEN 2014UCN Teknologi/act2learn11 public class MyList : IEnumerable, ICollection { List list; int n;//number of elements public MyList(int size) { list= new List (); n= 0; } You may want your container to fit into the Collections API Decide on an data representation. Use the type parameter as type Define the class with a type parameter

Do your own generic container: MyListProject MyListProject FEN 2014UCN Teknologi/act2learn12 public void Add(T o){ list.Add(o); n++; } public T Get(int i){ return list[i]; } public IEnumerator GetEnumerator(){ return list.GetEnumerator(); } public bool Contains(T item){ throw new NotImplementedException(); } Implement the methods (all of them )

Do your own generic container: MyListProject MyListProject FEN 2014UCN Teknologi/act2learn13 static void Main(string[] args) { MyList l= new MyList (10); l.Add(1); l.Add(2); l.Add(3); Console.WriteLine("Count : "+ l.Count); foreach(int x in l) Console.WriteLine(x); Console.ReadLine(); } Use it like any other generic collection

Do your own generic container: MyListProject MyListProject FEN 2014UCN Teknologi/act2learn14 You may want to do your own iterator In MyList

Generics with constrains on type parameters It’s possible to specify that the type parameter should implement certain interfaces: Only key types (K) that implements IComparable are allowed. FEN 2014UCN Teknologi/act2learn15 public class LinkedList where K : IComparable { T Find(K key) { Node current = m_Head; while(current.NextNode != null) { if(current.Key.CompareTo(key) == 0) break; else current = current.NextNode; } return current.Item; } //Rest of the implementation } // from: