Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList.

Similar presentations


Presentation on theme: "Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList."— Presentation transcript:

1 Generics & Collection Classes Version 1.0

2 Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList

3 Objectives After completing this topic, students should be able to: Correctly design and use generic methods and generic classes Correctly design and use classes that use the generic collection classes in a C# program * Know how to correctly use an List * know how to correctly use a Queue * Know to correctly use a Stack * Know how to correctly use a LinkedList * Know how to correctly use an enumerator

4 Generic Methods In a normal method we use parameters to tell the method what values to use. A Generic Method lets us parameterize the type of data that the method will use.

5 Example Assume that you want to have method that swaps two int values so you can use it to sort an array of int types. static void Swap(ref int lhs, ref int rhs) { int tempVal = lhs; lhs = rhs; rhs = tempVal; } int[] iArray = { 30, 100, 10, 200, 5, 500 }; Swap(ref iArray[0],ref iArray[1]);

6 Make it Generic Now what if you want to generalize the method so that it swaps two values of any type. static void Swap (ref T lhs,ref T rhs) { T tempVal = lhs; lhs = rhs; rhs = tempVal; } int[] iArray = { 30, 100, 10, 200, 5, 500 }; Swap(ref iArray[0],ref iArray[1]); Add to method name

7 Make it Generic static void Swap (ref T lhs,ref T rhs) { T tempVal = lhs; lhs = rhs; rhs = tempVal; } int[] iArray = { 30, 100, 10, 200, 5, 500 }; Swap(ref iArray[0],ref iArray[1]); Change int to T

8 Just like you can create a generic method, it is possible to create a generic class. One or more of the data members of a generic class will be parameterized.

9 Generic Class Example A box of …

10 class Box { private T theContent;... } The class is parameterized with It has a data member of type T

11 Create a Box containing an int like this … Box boxOfInt = new Box (6); The data type is int

12 Create a Box containing a double like this … Box boxOfInt = new Box (6.5); The data type is double

13 Class Constructor public Box(T theParameter) { theContent = theParameter; } data type is parameterized

14 A Getter and a Setter public T getContent() { return theContent; } public void setContent(T theParameter) { theContent = theParameter; } returns data of type T Takes a parameter of type T

15 The Complete Class class Box { private T theContent; public Box(T theParameter) { theContent = theParameter; } public T getContent() { return theContent; } public void setContent(T theParameter) { theContent = theParameter; }

16 static void Main() { Box boxOfInt = new Box (6); boxOfInt.setContent(6); Console.WriteLine(boxOfInt.getContent()); Console.ReadLine(); } A Small Driver

17 A More Complex Example Create a dynamic array of T’s

18 A More Complex Example class DArray { private static int DSIZE = 5; private T[] _TArray; private T[] _TempArray; private int _Capacity; private T _TempVal; public Capacity… //property public Count…//property public Darray()… //constructor public void Swap(int,int)… //method private void Resize()… //method public void AddData(T)… //method public T GetData()… //method }

19 class Darray { private static int DSIZE = 5; private T[] _TArray; private T[] _TempArray; private int _Capacity; public int Capacity { get { return _Capacity; } } private int _Count; public int Count { get { return _Count; } } private T _TempVal; public DArray() { _Capacity = DSIZE; _Count = 0; _TArray = new T[_Capacity]; } public void Swap(int fval,int sval) { _TempVal = _TArray[fval]; _TArray[fval] = _TArray[sval]; _TArray[sval] = _TArray[fval]; } private void Resize() { _TempArray = new T[_Capacity * 2]; _TArray.CopyTo(_TempArray, 0); _TArray = _TempArray; _TempArray = null; _Capacity *= 2; } public void AddData(T aval) { if (_Count >= _Capacity) Resize(); _TArray[_Count++] = aval; } public T GetData(int pos) { if (pos >= 0 && pos <= _Count) return _TArray[pos]; else throw new Exception("Invalid index error"); } }//end class DArray

20 Generic Collection Classes Name of the class is Stuff Valid generic datatypes are now T,K,Q,W Stuff is meta class and becomes a real Class when we create a real type i.e. Stuff rref; The name of the real class is Stuff

21 Up to this point, if we wanted a program to deal with a collection of objects, we had to use an array. An array is limited, because we have to define its size when it is created, and once created the size of the array cannot be changed. The Generic Collection classes do not have this restriction. An array is what is known as a collection class, because it can hold a collection of objects. C# provides several other collection classes. A collection class uses the has-a relationship known as composition. An array has-a int as an element if it is an array of int’s or has a Data object as an element if it is an array of Data objects.

22 List Queue Stack LinkedList Some C# Generic Collection Classes

23 List An List works much like an array, but its size changes dynamically as new data is stored in it. When you create an List you must specify the datatype of T and you may or may not specify its initial capacity. i.e. List ilist = new List (); //default Capacity = 0 or List ilist = new List (5); //Capacity = 5 after Add 01230123

24 List using System; using System.Collections.Generic; //You need to use this namespace static class MProgram { const int MAX = 4; static void Main() { List myData = new List (); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); for(int idx=0; idx<MAX; idx++) myData.Add(idx+4); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); myData.Add(12); //Capacity doubles to 8 Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); foreach (int i in myData) Console.WriteLine("The data is {0}", i); Console.ReadLine(); }//End Main() }//End class MProgram

25 List using System; using System.Collections.Generic; static class MProgram { const int MAX = 4; static void Main() { List myData = new List (); //Create object of List T is now int Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); for(int idx=0; idx<MAX; idx++) myData.Add(idx+4); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); myData.Add(12); //Capacity doubles to 8 Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); foreach (int i in myData) Console.WriteLine("The data is {0}", i); Console.ReadLine(); }//End Main() }//End class MProgram

26 List using System; using System.Collections.Generic; static class MProgram { const int MAX = 4; static void Main() { List myData = new List (); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); for(int idx=0; idx<MAX; idx++) //Initial Capacity = 0 and becomes 4 after Add myData.Add(idx+4); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); myData.Add(12); //Capacity doubles to 8 Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); foreach (int i in myData) Console.WriteLine("The data is {0}", i); Console.ReadLine(); }//End Main() }//End class MProgram

27 List using System; using System.Collections.Generic; static class MProgram { const int MAX = 4; static void Main() { List myData = new List (); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); for(int idx=0; idx<MAX; idx++) myData.Add(idx+4); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); myData.Add(12); //Capacity doubles to 8 with this Add Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); foreach (int i in myData) Console.WriteLine("The data is {0}", i); Console.ReadLine(); }//End Main() }//End class MProgram

28 List using System; using System.Collections.Generic; static class MProgram { const int MAX = 4; static void Main() { List myData = new List (); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); for(int idx=0; idx<MAX; idx++) myData.Add(idx+4); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); myData.Add(12); Console.WriteLine("List Capacity={0} & Count={1}", myData.Capacity, myData.Count); foreach (int i in myData)//Outputs 4, 5, 6, 7, 12 (Capacity=8 Count=5) Console.WriteLine("The data is {0}", i); Console.ReadLine(); }//End Main() }//End class MProgram

29 Some Other List Methods Clear( ) - removes all elements from the List and sets Capacity = 0 Insert( pos, value ) - inserts value at position pos in the List RemoveAt( pos ) - removes the element at the specified position For List myData = new List (5); myData[1] = 100; sets the value of the second element to 100

30 Some List Properties Capacity – number of items that the List can hold Count – the number of items currently in the List item[index] - element at index

31 List myData = new List (); myData.Add(4); myData.Add(12); Console.WriteLine(myData.Capacity); Console.WriteLine(myData.Count); capacity will be 4 count will be 2

32 You can use square brackets [ ] to access data in an List, but the index must be within the current size (count) of the List.

33 List myData = new List (); myData.Add(4); myData.Add(12); Console.WriteLine(myData[1]); Console.WriteLine(myData[2]); this will output 12 this will throw an exception

34 Enumerators The collection classes in C# all support the IEnumerator Interface. Current – a property that returns the current element MoveNext – a method that moves the enumerator to the next element in the collection Reset – moves the enumerator to its initial position, before the first element

35 Enumerator Example List myData = new List (); myData.Add(4); myData.Add(12); myData.Add(16); myData.Add(21); IEnumerator enumer = myData.GetEnumerator(); while (enumer.MoveNext()) Console.WriteLine(enumer.Current); The GetEnumerator method in the List class returns an IEnumerator object. It initially points one place before the first element of the list.

36 Enumerator Example List myData = new List (); myData.Add(4); myData.Add(12); myData.Add(16); myData.Add(21); IEnumerator enumer = myData.GetEnumerator(); while (enumer.MoveNext()) Console.WriteLine(enumer.Current); The MoveNext method in IEnumerator moves the enumerator to the next element in the ArrayList. If the element exists the method returns true. If it moves out of range, it returns false. You can test this with a while condition.

37 Enumerator Example List myData = new List (); myData.Add(4); myData.Add(12); myData.Add(16); myData.Add(21); IEnumerator enumer = myData.GetEnumerator(); while (enumer.MoveNext()) Console.WriteLine(enumer.Current); The Current property in the enumerator provides access to the element in the ArrayList that the enumerator currently points to.

38 Queue A queue represents a first-in, first-out (FIFO) generic collection. The classic analogy is to a line at a ticket window. The first person to join the line ought to be the first person to come off the line to buy a ticket. 0 12 345

39 Queue A queue includes the following properties and methods: Count – this property contains the number of elements in the queue Enqueue – this method adds an element to the end of the queue Dequeue – this method removes and returns an element from the front of the queue

40 Stack A stack represents a last-in, first-out (FIFO) generic collection. The classic analogy is the stack of plates in the cafeteria. The first plate put on the stack will be the last one to be removed. 0 1 2 3

41 Stack A stack includes the following properties and methods: Count – this property contains the number of elements in the queue Push – this method adds an element to the top of the stack Pop – this method removes and returns the element on the top of the stack.

42 LinkedList A linkedlist represents a doubly linked generic collection. The linkedlist becomes a chain of objects where each object contains a forward link to the next object and a back link to the previous object. reverse link null forward link null

43 LinkedList Useful LinkedList methods and properties Constructor LinkedList () Creates an empty linkedlist

44 LinkedList Useful LinkedList methods and properties Methods Clear- Removes all nodes from the LinkedList Find - Finds the first node that contains the specified value. FindLast - Finds the last node that contains the specified value Remove(T) - Removes the first occurrence of the specified value from the LinkedList. Remove(LinkedListNode ) - Removes the specified node from the LinkedList. RemoveFirst - Removes the node at the start of the LinkedList. RemoveLast - Removes the node at the end of the LinkedList.

45 LinkedList Useful LinkedList methods and properties Properties Count - Gets the number of nodes actually contained in the LinkedList. First - Gets the first node of the LinkedList. Last - Gets the last node of the LinkedList.


Download ppt "Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList."

Similar presentations


Ads by Google