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.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Generics, Lists, Interfaces
Data Structures and Collections
Generics and the ArrayList Class
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
 2006 Pearson Education, Inc. All rights reserved Collections.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
 2006 Pearson Education, Inc. All rights reserved Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 2006 Pearson Education, Inc. All rights reserved Collections Many slides modified by Prof. L. Lilien (even many without an explicit message indicating.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
C# Programming: From Problem Analysis to Program Design1 Advanced Collections C# Programming: From Problem Analysis to Program Design 3 rd Edition 8.
 2006 Pearson Education, Inc. All rights reserved Generics.
Chapter 19 Java Data Structures
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
XML files (with LINQ). Introduction to LINQ ( Language Integrated Query ) C#’s new LINQ capabilities allow you to write query expressions that retrieve.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
 2005 Pearson Education, Inc. All rights reserved Generics.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Chapter 18 Java Collections Framework
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Understanding Data Types and Collections Lesson 2.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CIS 270—Application Development II Chapter 18-Generics.
Arrays and Collections Tonga Institute of Higher Education.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Interface: (e.g. IDictionary) Specification class Appl{ ---- IDictionary dic; dic= new XXX(); application class: Dictionary SortedDictionary ----
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
C# Collections & Generics C#.NET Software Development Version 1.0.
Session 07 Module 13 - Collections. Collections / Session 7 / 2 of 32 Review  A delegate in C# is used to refer to a method in a safe manner.  To invoke.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
1 9/22/05CS360 Windows Programming Arrays, Collections, Hash Tables, Strings.
Object Oriented Software Development 6. Arrays and collections.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
C# Collections & Generics
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Understanding Data Types and Collections Lesson 2.
Lecture 10 Collections Richard Gesick.
Sort & Search Algorithms
Advanced .NET Programming I 2nd Lecture
Chapter 20 Generic Classes and Methods
Chapter 5: Programming with C#
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Collections 24: Collections Programming C# © 2003 DevelopMentor, Inc.
CS313D: Advanced Programming Language
Lesson 6. Types Equality and Identity. Collections.
Object Oriented Programming in java
Introduction to Data Structure
Fundaments of Game Design
Presentation transcript:

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. Example: We write a generic method for sorting an array of objects, then call the generic method with an array of any type. The compiler performs type checking to ensure that the array passed to the sorting method contains only elements of the same type. Generics provide compile-time type safety.

Generic Methods Generic methods enable you to specify, with a single method declaration, a set of related methods. Example: OverloadedMethods.cs Note that the array element type (int, double or char) appears only once in each method—in the method header. If we replace the element types in each method with a generic name then all three methods would look like follows: private static void DisplayArray( T[] inputArray ) { foreach ( T element in inputArray ) Console.Write( element + " " ); Console.WriteLine( "\n" ); } However, it will not compile, because its syntax is not correct. GenericMethods.cs

Generic Methods All generic method declarations have a type-parameter list delimited by angle brackets that follows the method’s name. Each type-parameter list contains one or more type parameters. A type parameter is an identifier that is used in place of actual type names. The type parameters can be used to declare the return type, the parameter types and the local variable types in a generic method declaration. Type parameters act as placeholders for type arguments that represent the types of data that will be passed to the generic method. A generic method’s body is declared like that of any other method. The type-parameter names throughout the method declaration must match those declared in the type-parameter list. A type parameter can be declared only once in the type-parameter list but can appear more than once in the method’s parameter list. You can also use explicit type arguments to indicate the exact type that should be used to call a generic function, as in DisplayArray ( intArray );

Generic Classes A generic class describes a class in a type-independent manner. We can then instantiate type-specific objects of the generic class. Let’s look at example: Stack.sln StackTest.cs: repeats code in TestPopInt / TestPopDouble and TestPushInt / TestPushDouble How to fix this? Let’s code this together first. NewStackTest.cs

Generic Interfaces In NewStackTest.cs, we used a generic interface: IEnumerable Similar to generic classes, generic interfaces enable you to specify, with a single interface declaration, a set of related interfaces.

Common Data Structures - summary We’ve seen Array only so far  fixed-size (can grow with Resize) Dynamic data structures can automatically grow and shrink at execution time. Linked lists are collections of data items that are “chained together”. Stacks have insertions and deletions made at only one end: the top. Queues represent waiting lines; insertions are made at the back and deletions are made from the front. Binary trees facilitate high-speed searching and sorting of data.

Collections For the vast majority of applications, there is no need to build custom data structures. Instead, you can use the prepackaged data-structure classes provided by the.NET Framework. These classes are known as collection classes—they store collections of data. Each instance of one of these classes is a collection of items. Collection classes enable programmers to store sets of items by using existing data structures, without concern for how they are implemented. System.Collections contains collections that store references to objects. System.Collections

ArrayList The ArrayList collection class is a conventional arrays and provides dynamic resizing of the collection. Method / PropertyDescription Add Adds an object to the end of the ArrayList.ArrayList Capacity Property that gets and sets the number of elements for which space is currently reserved in the ArrayList. Clear Removes all elements from the ArrayList.ArrayList Contains Determines whether an element is in the ArrayList.ArrayList Count Read-only property that gets the number of elements stored in the ArrayList. IndexOf Returns the zero-based index of the first occurrence of a value in the ArrayList ArrayList Insert Inserts an element into the ArrayList at the specified index.ArrayList Remove Removes the first occurrence of a specific object from the ArrayList.ArrayList RemoveAt Removes the element at the specified index of the ArrayList.ArrayList TrimToSize Sets the capacity to the actual number of elements in the ArrayList.ArrayList

Let’s write code to use ArrayList. Suppose we have two color string arrays as follows: private static readonly string[] colors = { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" }; private static readonly string[] removeColors = { "RED", "WHITE", "BLUE" }; 1. Let’s create an arrayList and add items in colors into it. 2. Let’s display the size and capacity of arrayList. 3. Let’s find the index of the item “BLUE”. 4. Let’s write a method that removes the items in one ArrayList from another. And then call that method to remove removeColors array from our first arrayList. 5. ArrayListTest.cs

Generic Collections Problems with Nongeneric Collections Having to store data as object references causes less efficient code due to unboxing. The.NET Framework also includes the System.Collections.Generic namespace, which uses C#’s generics capabilities. Many of these new classes are simply generic counterparts of the classes in namespace System.Collections. Generic collections eliminate the need for explicit type casts that decrease type safety and efficiency. Generic collections are especially useful for storing structs, since they eliminate the overhead of boxing and unboxing.

SortedDictionary A dictionary is the general term for a collection of key/value pairs. A hash table is one way to implement a dictionary. Example: Let’s write a program that counts the number of occurrences of each word in a string read from console using SortedDictionary. To split the sentence into words, we will use this: // split input text into tokens string[] words = Regex.Split( ); Members:

Collection Interfaces All collection classes in the.NET Framework implement some combination of the collection interfaces. InterfaceDescription ICollection The root interface from which interfaces IList and IDictionary inherit. Contains a Count property to determine the size of a collection and a CopyTo method for copying a collection’s contents into a traditional array. IList An ordered collection that can be manipulated like an array. Provides an indexer for accessing elements with an int index. Also has methods for searching and modifying a collection, including Add, Remove, Contains and IndexOf. IEnumerable An object that can be enumerated. This interface contains exactly one method, GetEnumerator, which returns an IEnumerator object. ICollection implements IEnumerable, so all collection classes implement IEnumerable directly or indirectly. IDictionary A collection of values, indexed by an arbitrary “key” object. Provides an indexer for accessing elements with an object index and methods for modifying the collection (e.g., Add, Remove). IDictionary property Keys contains the objects used as indices, and property Values contains all the stored objects.

HashTable Arrays uses nonnegative integer indexes as keys. Sometimes associating these integer keys with objects to store them is impractical, so we develop a scheme for using arbitrary keys. When an application needs to store something, the scheme could convert the application key rapidly to an index. Once the application has a key for which it wants to retrieve the data, simply apply the conversion to the key to find the array index where the data resides. The scheme we describe here is the basis of a technique called hashing, in which we store data in a data structure called a hash table.

HashTable A hash function performs a calculation that determines where to place data in the hash table. The hash function is applied to the key in a key/value pair of objects. Class Hashtable can accept any object as a key. For this reason, class object defines method GetHashCode, which all objects inherit. Example: Let’s write a program that counts the number of occurrences of each word in a string read from console. To split the sentence into words, we will use this: // split input text into tokens string[] words = Regex.Split( ); HashTable solution.

HashTable Hashtable method ContainsKey determines whether a key is in the hash table. Read-only property Keys returns an ICollection that contains all the keys. Hashtable property Count returns the number of key/value pairs in the Hashtable. If you use a foreach statement with a Hashtable object, the iteration variable will be of type DictionaryEntry. The enumerator of a Hashtable (or any other class that implements IDictionary) uses the DictionaryEntry structure to store key/value pairs. This structure provides properties Key and Value for retrieving the key and value of the current element. If you do not need the key, class Hashtable also provides a read-only Values property that gets an ICollection of all the values stored in the Hashtable.

Stack & Queue Stack: Push Pop Peek Example: StackTest.cs Queue: Enqueue Dequeue Peek Exercise: re-write the StackTest.cs example at home using a Queue this time.

Generic Collection Interfaces InterfaceDescription ICollection(T) Defines methods to manipulate generic collections. IList(T) Represents a collection of objects that can be individually accessed by index. IEnumerable(T) Exposes the enumerator, which supports a simple iteration over a collection of a specified type. IEnumerator(T) Supports a simple iteration over a generic collection. IDictionary(TKey,TValue) Represents a generic collection of key/value pairs. IComparer(T) Defines a method that a type implements to compare two objects.

Other Generic Collection Classes List(T) Let’s re-write the ArrayListTest.cs using List this time. Stack(T) Queue(T) LinkedList(T) SortedList(TKey, TValue)