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

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
Chapter 24 Lists, Stacks, and Queues
Linked Lists Linear collections.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
CSE Lecture 12 – Linked Lists …
Generics, Lists, Interfaces
The List ADT Textbook Sections
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
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.
Queues. What is a queue? First-in first-out data structure (FIFO) New objects are placed at rear Removal restricted to front Examples?
Queues. What is a queue? First-in first-out data structure (FIFO) New objects are placed at rear Removal restricted to front Examples?
Chapter 12: Data Structures
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS 106 Introduction to Computer Science I 12 / 11 / 2006 Instructor: Michael Eckmann.
1 Data Structures  We can now explore some advanced techniques for organizing and managing information  Chapter 12 of the book focuses on: dynamic structures.
TCSS 342, Winter 2005 Lecture Notes
CSC 212 Stacks & Queues. Announcement Daily quizzes accepted electronically only  Submit via one or other Dropbox  Cannot force you to compile & test.
Chapter 12 Collections. © 2004 Pearson Addison-Wesley. All rights reserved12-2 Collections A collection is an object that helps us organize and manage.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
CS 106 Introduction to Computer Science I 12 / 13 / 2006 Instructor: Michael Eckmann.
© 2004 Pearson Addison-Wesley. All rights reserved12-1 Chapter 12 : Collections Intermediate Java Programming Summer 2007.
Data Structures Data structures permit the storage of related data for use in your program. –Arrays.
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
CS 1031 Queues Definition of a Queue Examples of Queues Design of a Queue Class Different Implementations of the Queue Class.
© 2006 Pearson Education Chapter 12: Data Structures Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
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.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
CMSC 202 Stacks and Queues. What’s a Queue? A queue is a linear collection of homogeneous data in which items added to the queue must be placed at the.
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Chapter 12 Collections. © 2004 Pearson Addison-Wesley. All rights reserved12-2 Collections A collection is an object that helps us organize and manage.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved12-2 Agenda Questions? Problem set 5 Parts A & B Corrected  Good results  2 A’s, 1.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Understanding Data Types and Collections Lesson 2.
Chapter 12: Collections by Lewis and Loftus (Updated by Dan Fleck) Coming up: Collections.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Stacks And Queues Chapter 18.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Arrays and Collections Tonga Institute of Higher Education.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Week 5 - Wednesday.  What did we talk about last time?  Recursion  Definitions: base case, recursive case  Recursive methods in Java.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Queues Chapter 5 Queue Definition A queue is an ordered collection of data items such that: –Items can be removed only at one end (the front of the queue)
Object Oriented Software Development 6. Arrays and collections.
CH 5 : STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
CS-2851 Dr. Mark L. Hornick 1 Stacks and Queues Behavior vs. Structure.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
1 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Jung Soo (Sue) Lim Cal State LA.
Chapter 18: Stacks and Queues.
Linked Lists, Stacks and Queues Textbook Sections
Chapter 19: Stacks and Queues.
Lecture 10 List Richard Gesick.
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
More Data Structures (Part 1)
Fundaments of Game Design
Data Structures & Programming
Presentation transcript:

Generics & Collection Classes Version 1.0

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

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

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.

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]);

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

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

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.

Generic Class Example A box of …

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

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

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

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

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

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; }

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

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

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 }

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

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

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.

List Queue Stack LinkedList Some C# Generic Collection Classes

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

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

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

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

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

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

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

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

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

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

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

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

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.

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.

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.

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

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

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

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.

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

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

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.

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.