Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Data Collections

Similar presentations


Presentation on theme: "Advanced Data Collections"— Presentation transcript:

1 Advanced Data Collections
INF230 Basics in C# Programming AUBG, COS dept Lecture 33 Title: Advanced Data Collections Reference: Doyle, chap 8

2 Lecture Contents: String class Other Collection classes BitArray
HashTable Linked List Queue Stack

3 From Problem Analysis to Program Design
Chapter 8 Advanced Collections C# Programming: From Problem Analysis to Program Design 4th Edition

4 Array Class (given Arrays p1 )
. C# Programming: From Problem Analysis to Program Design

5 Array Class (given Arrays p1 )
Base array class All languages that target Common Language Runtime More power is available with minimal programming C# Programming: From Problem Analysis to Program Design

6 Table 7-1 System.Array methods
C# Programming: From Problem Analysis to Program Design

7 Table 7-1 System.Array methods (continued)
C# Programming: From Problem Analysis to Program Design

8 Table 7-1 System.Array methods
C# Programming: From Problem Analysis to Program Design

9 Table 7-1 System.Array methods
C# Programming: From Problem Analysis to Program Design

10 Array Class (continued)
// Copies 5 values from waterDepth, beginning at index location 2. Place // values in Array W, starting at index location 0. Array.Copy (waterDepth, 2, w, 0, 5); Array.Sort (w); // Sorts Array w in ascending order outputMsg = "Array w Sorted\n\n"; // Displays Array w sorted foreach(double wVal in w) { if (wVal > 0) outputMsg += wVal + "\n"; } C# Programming: From Problem Analysis to Program Design

11 ArrayList Class (given Arrays p2 )
. C# Programming: From Problem Analysis to Program Design

12 ArrayList Class (given Arrays p2 )
Limitations of traditional array Cannot change the size or length of an array after it is created ArrayList class facilitates creating listlike structure, AND it can dynamically increase or decrease in length Similar to vector class found in other languages Includes large number of predefined methods using System.Collections; C# Programming: From Problem Analysis to Program Design

13 ArrayList Class (continued)
Table 8-1 ArrayList members C# Programming: From Problem Analysis to Program Design

14 ArrayList Class (continued)
Table 8-1 ArrayList members (continued) C# Programming: From Problem Analysis to Program Design

15 ArrayList Class (continued)
Table 8-1 ArrayList members (continued) C# Programming: From Problem Analysis to Program Design

16 ArrayList Class (continued)
Any predefined or user-defined type can be used as an ArrayList object C# also includes a List<> class List<> class requires that objects be the same type when you place them in the structure ArrayList allows you to mix types C# Programming: From Problem Analysis to Program Design

17 ArrayList Class (continued)
ArrayList anArray = new ArrayList( ); // Instantiates ArrayList anArray.Add("Today is the first day of the rest of your life!"); anArray.Add("Live it to the fullest!"); anArray.Add("ok"); anArray.Add("You may not get a second chance."); anArray.RemoveAt(2); // Removes the third physical one for (int i = 0; i < ar.Count; i++) //Displays elements Console.WriteLine(ar[i] ); C# Programming: From Problem Analysis to Program Design

18 ArrayList Class (continued)
anArray.Sort(); for (k = 0; k < anArray.Count; k++) //Displays elements Console.WriteLine(anArray[k]); anArray.Reverse(); Console.WriteLine(anArray.Capacity +" " + anArray.Count); C# Programming: From Problem Analysis to Program Design

19 ArrayList Class (continued)
using System; using System.Collections; class SBArrayList { static void Main(string[] args) ArrayList ar = new ArrayList(); ar.Add("Sofia"); ar.Add("Varna"); ar.Add("Bourgas"); for (int i = ar.Count-1; i>=0; i--) Console.Write(ar[i] + " "); ar.Remove("Varna"); Console.WriteLine(); } C# Programming: From Problem Analysis to Program Design

20 String Class Stores a collection of Unicode characters
Immutable series of characters Reference type Normally equality operators like == and != compare the object’s references, but equality operators function differently with string symbolic data than with other reference objects Equality operators == and != are defined to compare the contents or values Includes large number of predefined methods C# Programming: From Problem Analysis to Program Design

21 String Class Can process variables of string type as a group of characters Can also access individual characters in string using an index with [ ] First character is indexed by zero string sValue = "C# Programming"; object sObj; string s = "C#"; C# Programming: From Problem Analysis to Program Design

22 Table 8-2 Members of the string class
C# Programming: From Problem Analysis to Program Design

23 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

24 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

25 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

26 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

27 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

28 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

29 Table 8-2 Members of the string class (continued)
C# Programming: From Problem Analysis to Program Design

30 String Class Class methods, such as Compare, Concat, and Copy, prefix the name of the method in the call with the string data type (e.g. s = string.Copy(sValue);). Most string member arguments that take a string object accept a string literal @-quoted string literals, start with symbol \t world"); //Displays hello \t world C# Programming: From Problem Analysis to Program Design

31 Other Collection Classes
Collection classes are classes that enable you to store and retrieve various groups of objects Number of other predefined collection classes Classes for Storing bit values Creating hash tables Creating lists, stacks, queues C# Programming: From Problem Analysis to Program Design

32 BitArray class The BitArray class stores a collection of bit values.
These bit values are represented as Booleans, where true indicates that the bit is on and false indicates that the bit is off. FYI: Data type bool is defined as struct System.Boolean, i.e. bool and Boolean are synonyms There are several ways to create and initialize BitArrays Using System.Collections; is must C# Programming: From Problem Analysis to Program Design

33 BitArray class Include the System.Collections namespace
// Creates and initializes several BitArrays BitArray firstBitArr = new BitArray(10); BitArray secondBitArr = new BitArray(10, true); bool[ ] boolArray = new bool[5] {true, false, true, true, false}; BitArray thirdBitArr = new BitArray(boolArray); Count and Length properties Item property C# Programming: From Problem Analysis to Program Design

34 BitArray class There are a number of constructors with this collection. // Creates and initializes several BitArrays // integer 10 specifies the number of elements, // all set by default to False BitArray firstBitArr = new BitArray(10); C# Programming: From Problem Analysis to Program Design

35 BitArray class Include the System.Collections namespace
// Creates and initializes several BitArrays // integer 10 specifies the number of elements, // all set explicitly to True BitArray secondBitArr = new BitArray(10, true); C# Programming: From Problem Analysis to Program Design

36 BitArray class Include the System.Collections namespace
// Creates and initializes several BitArrays Another option is to use array of Booleans to set the valuues bool[ ] boolArray = new bool[5] {true, false, true, true, false}; BitArray thirdBitArr = new BitArray(boolArray); C# Programming: From Problem Analysis to Program Design

37 BitArray class (continued)
Set( ) and SetAll( ) methods used to change values of elements within a BitArray. // set all elements to true firstBitArr.SetAll(true); foreach (Boolean x in firstBitArr) Console.Write(" {0}", x); // set the first and second element to false firstBitArr[0] = false; firstBitArr.set(1, false); C# Programming: From Problem Analysis to Program Design

38 BitArray class (continued)
BitArrays most commonly used to represent a simple group of Boolean flags BitArrays useful for working with large data sets BitArrays compactly store individual bits as Boolean values C# Programming: From Problem Analysis to Program Design

39 HashTable class Hashtable already introduced once in lecture on Arrays (part 2) Topic: Associative Arrays More details follow C# Programming: From Problem Analysis to Program Design

40 HashTable class Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key Hash code - a number generated by a hashing function(algorithm) using a key as argument with the objective of providing efficient insertion and find operations The goal is to design an algorithm that provides as few collisions as possible Strategies for resolving the collisions Rehashing or list of values with same hash code Do not have to create your own algorithm when you use the .NET Hashtable class C# Programming: From Problem Analysis to Program Design

41 HashTable class (continued)
// Creates a new hash table Hashtable executableProgram = new Hashtable(); // Add some elements to the hash table. There are no // duplicate keys, but some of the values are duplicates. executableProgram.Add("pdf", "acrord32.exe"); executableProgram.Add("tif", "snagit32.exe"); executableProgram.Add("jpg", "snagit32.exe"); executableProgram.Add("sln", "devenv.exe"); executableProgram.Add("rtf", "wordpad.exe"); // read a value using key as index string data type Console.WriteLine(executableProgram["jpg"]); C# Programming: From Problem Analysis to Program Design

42 HashTable class (continued)
To write your own hash algorithm, override the GetHashCode( ) method and provide a new algorithm for the hash function Should also override the Equals( ) method to guarantee that two objects considered equal have the same hash code C# Programming: From Problem Analysis to Program Design

43 HashTable class (continued)
Has properties and methods of Add( ) Clear( ) Contains( ) Count Keys Item Remove( ) Values C# Programming: From Problem Analysis to Program Design

44 HashTable class (continued)
Also named Map Dictionary Associative Array C# Programming: From Problem Analysis to Program Design

45 Linked List Linked lists have additional field that contains a reference (link) to next record in the sequence Records do not have to be physically stored beside each other to retain their order Enables insertion and removal of records at any point in the list Insertion involves adjustment of links to point to newly inserted element Deletion involves adjustment of links to not point to deleted node C# Programming: From Problem Analysis to Program Design

46 Dynamic Data Structures
Linked list is example of dynamic data structure Linked list Node Node Node Pointer Pointer

47 Queue First-In-First-Out (FIFO) collection of objects
Useful for storing objects in the order they were received for sequential processing Capacity of a queue is the number of elements the queue can hold Enqueue( ) adds an object to the end of the queue Dequeue( ) removes and returns object at the beginning of the queue C# Programming: From Problem Analysis to Program Design

48 Queue Using System.Collections; // queue with double data type elements only Queue<double> q = new Queue<double>(4); q.Enqueue(5.5); double ddd = q.Dequeue(); ddd = q.Dequeue(); C# Programming: From Problem Analysis to Program Design

49 Figure 13.12 Queue of customers

50 Stack Last-in-first-out (LIFO) collection of objects
As elements are added, the capacity is automatically increased Push( ) adds an object to the end of the stack Pop( ) removes and returns the object to the beginning of the stack Peak( ) returns the object at the beginning of the stack without removing it Queue also has a Peak( ) method C# Programming: From Problem Analysis to Program Design

51 Stack Using System.Collections; // stack with any object data type elements Stack s = new Stack(10); s.Push(33); int dd = (int)s.Pop(); //dd = (int)s.Pop(); C# Programming: From Problem Analysis to Program Design

52 A Stack of Characters * C + 2 s

53 Example x = s.top( ); // stores ‘*’ into x, stack unchanged
s.pop( ); // removes top of stack s.push(‘/’); // adds ‘/’ to top of stack * C + 2 / C + 2 C + 2 s s s

54 Other Collection Classes
Dictionary - has much of the same functionality as the Hashtable class Generic class that provides a mapping from a set of keys to a set of values Add( ) method Item property Reference and retrieve values from the collection using its Keys and Values properties C# Programming: From Problem Analysis to Program Design

55 Exercises Design your own UDT class SBStack Data members: Methods
int[] p - stack memory space int sp - stack pointer Methods Constructor(s) void push(int pa) int pop() No tests “Stack overflow” in method push() No tests “Stack empty” in method pop() C# Programming: From Problem Analysis to Program Design

56 Exercises Modify the SBStack class to be a base class
Design a derived class SBStack2 from SBStack class Data members: No data members Methods Constructor(s) void push(int pa) // override base push() method with test “Stack overflow” int pop() // override pop() method with test “Stack empty” C# Programming: From Problem Analysis to Program Design

57 Linked list – dynamic data structure
Example – practical task Build a linked list of 3 nodes. The list structure: node a(10) -> node b(20) -> node c(30) -> NULL Create a program to traverse all list nodes from head to tail

58 Linked list – dynamic data structure
Composition /structure/ of a single node: Information component – int info; Control component – pointer to a node class Node { private int info; private Node ptr; public Node(int info) this.info = info; this.ptr = null; } public int getInfo() { return this.info; } public void setInfo(int par) { this.info = par; } public Node getPtr() { return this.ptr; } public void setPtr(Node par) { ptr = par; }

59 Linked list – dynamic data structure
Create 3 separate independent nodes and initialize their info components Node a = new Node(10), b = new Node(20), c = new Node(30);

60 Linked list – dynamic data structure
Connect the nodes to build list a(10)->b(20)->c(30) a.setPtr(b); //a.ptr = b b.setPtr(c); c.setPtr(null);

61 Linked list – dynamic data structure
Traverse the list node by node start from head (node a) to tail (node c) Node begin; Node work; begin = a; work = begin; while (work != null) { Console.WriteLine(" {0}", work.getInfo()); work = work.getPtr(); }

62 Linked list – all the program 1/2
namespace SBthisPointer { class Node private int info; private Node ptr; public Node(int info) this.info = info; this.ptr = null; } public int getInfo() { return this.info; } public void setInfo(int par) { this.info = par; } public Node getPtr() { return this.ptr; } public void setPtr(Node par) { ptr = par; }

63 Linked list – all the program 2/2
class Program { static void Main(string[] args) { Node begin; Node work; Node a=new Node(10), b=new Node(20), c=new Node(30); a.setPtr(b); //a.ptr = b b.setPtr(c); c.setPtr(null); begin = a; work = begin; while (work != null) Console.WriteLine(" {0}", work.getInfo()); work = work.getPtr(); } } } } // end of namespace

64 Dynamic Data Structures
Type, compile and run the program ListThreeNodesTraverse.cs

65 13.6 Binary Trees Like a list with additional pointer
Nodes contain 2 pointers right pointer left pointer 0 (leaf nodes), 1, or 2 successor nodes Binary Tree empty root left and right sub-trees

66 Figure Binary trees

67 Thank You For Your Attention!


Download ppt "Advanced Data Collections"

Similar presentations


Ads by Google