generics collections

Download Generics collections

Post on 12-Jul-2015




3 download

Embed Size (px)


  • GenericsCollections

  • 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 MethodsGeneric methods enable you to specify, with a single method declaration, a set of related methods.Example: OverloadedMethods.csNote that the array element type (int, double or char) appears only once in each methodin 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 MethodsAll generic method declarations have a type-parameter list delimited by angle brackets that follows the methods 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 methods 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 methods parameter list.You can also use explicit type arguments to indicate the exact type that should be used to call a generic function, as inDisplayArray< int >( intArray );

  • Generic ClassesA generic class describes a class in a type-independent manner.We can then instantiate type-specific objects of the generic class.Lets look at example: Stack.sln

    StackTest.cs: repeats code in TestPopInt/TestPopDouble and TestPushInt/TestPushDoubleHow to fix this? Lets code this together first.NewStackTest.cs

  • Generic InterfacesIn NewStackTest.cs, we used a generic interface:IEnumerable < T >Similar to generic classes, generic interfaces enable you to specify, with a single interface declaration, a set of related interfaces.

  • Common Data Structures - summaryWeve 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.

  • CollectionsFor 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 classesthey 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.

  • ArrayListThe ArrayList collection class is a conventional arrays and provides dynamic resizing of the collection.

    Method / PropertyDescriptionAddAdds an object to the end of the ArrayList.CapacityProperty that gets and sets the number of elements for which space is currently reserved in the ArrayList.ClearRemoves all elements from the ArrayList.ContainsDetermines whether an element is in the ArrayList.CountRead-only property that gets the number of elements stored in the ArrayList.IndexOfReturns the zero-based index of the first occurrence of a value in the ArrayListInsertInserts an element into the ArrayList at the specified index.RemoveRemoves the first occurrence of a specific object from the ArrayList.RemoveAtRemoves the element at the specified index of the ArrayList.TrimToSizeSets the capacity to the actual number of elements in the ArrayList.

  • ArrayListLets 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" };

    Lets create an arrayList and add items in colors into it.Lets display the size and capacity of arrayList.Lets find the index of the item BLUE.Lets 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.ArrayListTest.cs

  • Generic CollectionsProblems with Nongeneric CollectionsHaving 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.

  • SortedDictionaryA dictionary is the general term for a collection of key/value pairs.A hash table is one way to implement a dictionary.Example: Lets 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 tokensstring[] words = Regex.Split( input, @"\s+" );

  • Collection InterfacesAll collection classes in the .NET Framework implement some combination of the collection interfaces.

    InterfaceDescriptionICollectionThe 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 collections contents into a traditional array.IListAn 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.IEnumerableAn 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.IDictionaryA 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.

  • HashTableArrays 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.

  • HashTableA 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: Lets 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 tokensstring[] words = Regex.Split( input, @"\s+" );HashTable solution.

  • HashTableHashtable 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 & QueueStack:PushPopPeekExample:StackTest.csQueue:EnqueueDequeuePeekExercise: re-write the StackTest.cs example at home using a Queue this time.

  • Generic Collection Interfaces

    InterfaceDescriptionICollection(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 e


View more >