Generics Collections

2,303 views
2,218 views

Published on

Published in: Technology, Education
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,303
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
154
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Generics Collections

  1. 1. Generics Collections
  2. 2. Why do we need Generics? <ul><li>Another method of software re-use. </li></ul><ul><li>When we implement an algorithm, we want to re-use it for different types . </li></ul><ul><li>Example: We write a generic method for sorting an array of objects, then call the generic method with an array of any type . </li></ul><ul><li>The compiler performs type checking to ensure that the array passed to the sorting method contains only elements of the same type . </li></ul><ul><li>Generics provide compile-time type safety. </li></ul>
  3. 3. Generic Methods <ul><li>Generic methods enable you to specify, with a single method declaration, a set of related methods. </li></ul><ul><li>Example: OverloadedMethods.cs </li></ul><ul><li>Note that the array element type (int, double or char) appears only once in each method—in the method header. </li></ul><ul><li>If we replace the element types in each method with a generic name then all three methods would look like follows: </li></ul><ul><ul><li>private static void DisplayArray( T [] inputArray ) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> foreach ( T element in inputArray ) </li></ul></ul><ul><ul><li> Console.Write( element + &quot; &quot; ); </li></ul></ul><ul><ul><li> Console.WriteLine( &quot; &quot; ); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>However, it will not compile, because its syntax is not correct. </li></ul><ul><li>GenericMethods.cs </li></ul>
  4. 4. Generic Methods <ul><li>All generic method declarations have a type-parameter list delimited by angle brackets that follows the method’s name. </li></ul><ul><li>Each type-parameter list contains one or more type parameters . </li></ul><ul><li>A type parameter is an identifier that is used in place of actual type names. </li></ul><ul><li>The type parameters can be used to declare the return type, the parameter types and the local variable types in a generic method declaration. </li></ul><ul><li>Type parameters act as placeholders for type arguments that represent the types of data that will be passed to the generic method. </li></ul><ul><li>A generic method’s body is declared like that of any other method. </li></ul><ul><li>The type-parameter names throughout the method declaration must match those declared in the type-parameter list. </li></ul><ul><li>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. </li></ul><ul><li>You can also use explicit type arguments to indicate the exact type that should be used to call a generic function, as in </li></ul><ul><ul><li>DisplayArray < int > ( intArray ); </li></ul></ul>
  5. 5. Generic Classes <ul><li>A generic class describes a class in a type-independent manner. </li></ul><ul><li>We can then instantiate type-specific objects of the generic class. </li></ul><ul><li>Let’s look at example: Stack.sln </li></ul><ul><li>StackTest.cs : repeats code in TestPop Int / TestPopDouble and TestPushInt / TestPush Double </li></ul><ul><li>How to fix this? Let’s code this together first. </li></ul><ul><li>NewStackTest.cs </li></ul>
  6. 6. Generic Interfaces <ul><li>In NewStackTest.cs , we used a generic interface: </li></ul><ul><ul><li>I E numerable < T > </li></ul></ul><ul><li>Similar to generic classes, generic interfaces enable you to specify, with a single interface declaration, a set of related interfaces. </li></ul>
  7. 7. Common Data Structures - summary <ul><li>We’ve seen Array only so far  fixed-size (can grow with Resize) </li></ul><ul><li>Dynamic data structures can automatically grow and shrink at execution time. </li></ul><ul><li>Linked lists are collections of data items that are “chained together”. </li></ul><ul><li>Stacks have insertions and deletions made at only one end: the top. </li></ul><ul><li>Queues represent waiting lines; insertions are made at the back and deletions are made from the front. </li></ul><ul><li>Binary trees facilitate high-speed searching and sorting of data. </li></ul>
  8. 8. Collections <ul><li>For the vast majority of applications, there is no need to build custom data structures. </li></ul><ul><li>Instead, you can use the prepackaged data-structure classes provided by the .NET Framework. </li></ul><ul><li>These classes are known as collection classes — they store collections of data. Each instance of one of these classes is a collection of items. </li></ul><ul><li>Collection classes enable programmers to store sets of items by using existing data structures, without concern for how they are implemented. </li></ul><ul><li>System.Collections contains collections that store references to objects. </li></ul>
  9. 9. ArrayList <ul><li>The ArrayList collection class is a conventional arrays and provides dynamic resizing of the collection. </li></ul>Method / Property Description Add Adds an object to the end of the 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 . Contains Determines whether an element is in the 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 Insert Inserts an element into the ArrayList at the specified index. Remove Removes the first occurrence of a specific object from the ArrayList . RemoveAt Removes the element at the specified index of the ArrayList . TrimToSize Sets the capacity to the actual number of elements in the ArrayList .
  10. 10. ArrayList <ul><li>Let’s write code to use ArrayList . </li></ul><ul><li>Suppose we have two color string arrays as follows: </li></ul><ul><li>private static readonly string[] colors = </li></ul><ul><li> { &quot;MAGENTA&quot;, &quot;RED&quot;, &quot;WHITE&quot;, &quot;BLUE&quot;, &quot;CYAN&quot; }; </li></ul><ul><li>private static readonly string[] removeColors = </li></ul><ul><li> { &quot;RED&quot;, &quot;WHITE&quot;, &quot;BLUE&quot; }; </li></ul><ul><li>Let’s create an arrayList and add items in colors into it. </li></ul><ul><li>Let’s display the size and capacity of arrayList . </li></ul><ul><li>Let’s find the index of the item “BLUE”. </li></ul><ul><li>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 . </li></ul><ul><li>ArrayListTest.cs </li></ul>
  11. 11. Generic Collections <ul><li>Problems with Nongeneric Collections </li></ul><ul><li>Having to store data as object references causes less efficient code due to unboxing. </li></ul><ul><li>The .NET Framework also includes the System.Collections.Generic namespace, which uses C#’s generics capabilities. </li></ul><ul><li>Many of these new classes are simply generic counterparts of the classes in namespace System.Collections . </li></ul><ul><li>Generic collections eliminate the need for explicit type casts that decrease type safety and efficiency. </li></ul><ul><li>Generic collections are especially useful for storing structs, since they eliminate the overhead of boxing and unboxing. </li></ul>
  12. 12. SortedDictionary<TKey, TValue> <ul><li>A dictionary is the general term for a collection of key/value pairs. </li></ul><ul><li>A hash table is one way to implement a dictionary. </li></ul><ul><li>Example: Let’s write a program that counts the number of occurrences of each word in a string read from console using SortedDictionary . </li></ul><ul><ul><li>To split the sentence into words, we will use this: </li></ul></ul><ul><ul><li>// split input text into tokens </li></ul></ul><ul><ul><li>string[] words = Regex.Split( input, @&quot;s+&quot; ); </li></ul></ul><ul><li>http://msdn.microsoft.com/en-us/library/xfhwa508.aspx </li></ul><ul><li>Members: </li></ul><ul><ul><li>http://msdn.microsoft.com/en-us/library/3eayzh46.aspx </li></ul></ul>
  13. 13. Collection Interfaces <ul><li>All collection classes in the .NET Framework implement some combination of the collection interfaces. </li></ul>Interface Description 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.
  14. 14. HashTable <ul><li>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. </li></ul><ul><li>When an application needs to store something, the scheme could convert the application key rapidly to an index . </li></ul><ul><li>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. </li></ul><ul><li>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 . </li></ul>
  15. 15. HashTable <ul><li>A hash function performs a calculation that determines where to place data in the hash table. </li></ul><ul><li>The hash function is applied to the key in a key/value pair of objects. </li></ul><ul><li>Class Hashtable can accept any object as a key. For this reason, class object defines method GetHashCode , which all objects inherit. </li></ul><ul><li>Example: Let’s write a program that counts the number of occurrences of each word in a string read from console. </li></ul><ul><li>To split the sentence into words, we will use this: </li></ul><ul><li>// split input text into tokens </li></ul><ul><li>string[] words = Regex.Split( input, @&quot;s+&quot; ); </li></ul><ul><li>HashTable solution. </li></ul>
  16. 16. HashTable <ul><li>Hashtable method ContainsKey determines whether a key is in the hash table. </li></ul><ul><li>Read-only property Keys returns an ICollection that contains all the keys. </li></ul><ul><li>Hashtable property Count returns the number of key/value pairs in the Hashtable. </li></ul><ul><li>If you use a foreach statement with a Hashtable object, the iteration variable will be of type DictionaryEntry . </li></ul><ul><li>The enumerator of a Hashtable (or any other class that implements IDictionary ) uses the DictionaryEntry structure to store key/value pairs. </li></ul><ul><li>This structure provides properties Key and Value for retrieving the key and value of the current element. </li></ul><ul><li>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. </li></ul>
  17. 17. Stack & Queue <ul><li>Stack: </li></ul><ul><ul><li>Push </li></ul></ul><ul><ul><li>Pop </li></ul></ul><ul><ul><li>Peek </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>StackTest.cs </li></ul></ul><ul><li>Queue : </li></ul><ul><ul><li>Enqueue </li></ul></ul><ul><ul><li>Dequeue </li></ul></ul><ul><ul><li>Peek </li></ul></ul><ul><li>Exercise: re-write the StackTest.cs example at home using a Queue this time. </li></ul>
  18. 18. Generic Collection Interfaces http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx Interface Description 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.
  19. 19. Other Generic Collection Classes <ul><li>List(T) </li></ul><ul><ul><li>Let’s re-write the ArrayListTest.cs using List<T> this time. </li></ul></ul><ul><li>Stack(T) </li></ul><ul><li>Queue(T) </li></ul><ul><li>LinkedList(T) </li></ul><ul><li>SortedList(TKey, TValue) </li></ul>

×