Collections Objectives Explore collections in System.Collections - - PDF document

collections objectives
SMART_READER_LITE
LIVE PREVIEW

Collections Objectives Explore collections in System.Collections - - PDF document

Collections Objectives Explore collections in System.Collections namespace memory management containment testing sorting traversal 2 Collection A collection stores a group of objects Provides operations to


slide-1
SLIDE 1

Collections

slide-2
SLIDE 2

Objectives

  • Explore collections in System.Collections namespace

– memory management – containment testing – sorting – traversal

2

slide-3
SLIDE 3

Collection

3

  • A collection stores a group of objects
  • Provides operations to manipulate contents

– add – remove – count? – contains? – traverse – sort

collection of strings "blue" "green" "yellow" "red"

slide-4
SLIDE 4

Motivation

  • Basic array is too simple for many applications

– efficient, easy to use, and typesafe – but fixed size

int[] a = new int[10]; a[0] = 17; a[1] = 99; ... int x = a[1]; foreach (int i in a) ...

array size fixed at creation

4

slide-5
SLIDE 5

Collection classes

5

  • Collection library offers many collections

– in namespace System.Collections – store object reference to be generic – perform memory management internally

  • Core classes:

– ArrayList – Stack – Queue – Hashtable

slide-6
SLIDE 6

ArrayList

  • ArrayList provides storage for sequence of elements

– duplicate values ok – data stored in array – array resized automatically as needed

using System.Collections; class Department { ArrayList employees = new ArrayList(); ... }

create ArrayList to store Employees

array of object references ArrayList

  • bject

employees

6

slide-7
SLIDE 7

ArrayList services

  • ArrayList is primary class to support concept of list

public class ArrayList : IList, ICloneable { int Add (object value) ... void Insert(int index, object value) ... void Remove (object value) ... void RemoveAt(int index) ... void Clear () ... bool Contains(object value) ... int IndexOf (object value) ...

  • bject this[int index] { get... set.. }

int Capacity { get... set... } void TrimToSize() ... ... } control of memory in underlying array add new elements remove containment testing read/write existing element

7

slide-8
SLIDE 8

ArrayList Add

  • Use Add method to add new element to ArrayList

– added at end

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); ...

element 0 element 1 element 2

8

slide-9
SLIDE 9

ArrayList Count

  • Count property records number of elements in ArrayList

– read only

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); int n = a.Count;

Count is 3

9

slide-10
SLIDE 10

ArrayList Insert

  • Use Insert method to insert new element into ArrayList

– specify data and index – index must be in range 0 through Count – index equal to Count means add to end – other elements shifted as needed to accommodate new one

10

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); a.Insert(2, "ccc");

insert at index 2

slide-11
SLIDE 11

ArrayList RemoveAt

  • Use RemoveAt method to remove element from ArrayList

– specify index in range 0 through Count-1 – other elements shifted to fill empty position

11

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); a.RemoveAt(1);

remove element at index 1

slide-12
SLIDE 12

ArrayList Remove

12

  • Use Remove method to remove element from ArrayList

– pass in element to remove – searches linearly through list – uses Equals method for comparison – removes first occurrence – other elements shifted to fill empty position

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); a.Remove("aaa");

remove element equal to "aaa"

slide-13
SLIDE 13

ArrayList Contains

  • Use Contains method to do containment test in ArrayList

– performs linear search through underlying array – uses Equals method to determine equality

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); if (a.Contains("aaa")) Console.WriteLine("found"); else Console.WriteLine("not found");

contains?

13

slide-14
SLIDE 14

ArrayList IndexOf

  • Use IndexOf method search for element index in ArrayList

– performs linear search through underlying array – uses Equals method to determine equality – returns index of first occurrence or -1 if not found

14

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); int i = a.IndexOf("aaa"); ...

returns 1

slide-15
SLIDE 15

ArrayList indexer

  • Can use indexer to get/set elements

– cannot use to add new elements – index must be in range 0 through Count-1

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); a[2] = "ccc"; string s = (string)a[2];

use Add to add new elements change existing element read existing element

15

slide-16
SLIDE 16

ArrayList Capacity

16

  • Capacity property used to control size of underlying array

– can specify initial value during creation – can get or set

  • ArrayList will adjust capacity automatically

– defaults to 16 and doubles whenever more space needed – should let list control capacity when size of dataset unknown

ArrayList a = new ArrayList(); ArrayList b = new ArrayList(50); b.Capacity = 100; int c = b.Capacity;

default capacity is 16 specify capacity of 50 set capacity to 100 get capacity

slide-17
SLIDE 17

Box/unbox

  • Collections store object reference

– value types boxed when added – unboxed using cast when retrieved

ArrayList a = new ArrayList(); int x = 7; a.Add(x); int y = (int)a[0];

boxed unboxed

17

slide-18
SLIDE 18

Enumeration

  • Collection contents traversed using enumerator

– IEnumerable defines how to get an enumerator – IEnumerator used to perform traversal and access data – gives read-only access – available on all collection types

public interface IEnumerable { IEnumerator GetEnumerator(); }

get enumerator from collection

public interface IEnumerator {

  • bject Current { get; }

bool MoveNext(); void Reset(); }

traverse access data

18

slide-19
SLIDE 19

Traversal with enumerator

19

  • Can traverse collection contents with enumerator
  • 1. get IEnumerator from collection with GetEnumerator()
  • 2. call MoveNext() on enumerator to advance to first element
  • 3. use read-only Current property to access element data
  • 4. call MoveNext() to advance to next element
  • 5. repeat while MoveNext() returns true

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); IEnumerator e = a.GetEnumerator(); while (e.MoveNext()) { string t = (string)e.Current; ... } access and cast return advance and test get enumerator from collection

slide-20
SLIDE 20

Traversal with foreach

  • Can traverse enumerable collection with foreach loop

– less code than using enumerator – convenient since cast performed implicitly – better than indexer since no chance of index error – gives read-only access

ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); foreach (string s in a) { ... }

handles loop and cast

20

slide-21
SLIDE 21

Sort

21

  • Can sort the contents of Array and ArrayList

– use variations on Sort method

  • Must provide comparison method

– can build in by implementing IComparable – can supply separate IComparer object – simple types have comparison built in

public class ArrayList : IList, ICloneable { void Sort() ... void Sort(IComparer comparer) ... void Sort(int index, int count, IComparer comparer) ... ... } built-in compare separate compare

slide-22
SLIDE 22

IComparable

  • Build in comparison code with IComparable.CompareTo

– return negative, zero, or positive to indicate relative order

class Student : IComparable { public string name; public int id; public int CompareTo(object o) { Student s = o as Student; if (this.id < s.id) return -1; if (this.id > s.id) return 1; return 0; } ... } cast this goes first parameter goes first equal

22

slide-23
SLIDE 23

Using IComparable

  • IComparable objects have CompareTo built in

– will be called by no argument Sort method

ArrayList students = new ArrayList(); Student ann = new Student("Ann", 8000); Student bob = new Student("Bob", 2000); students.Add(ann); students.Add(bob); students.Sort();

sort according to CompareTo

23

slide-24
SLIDE 24

IComparer

  • Separate comparison code with IComparer.Compare

– return negative, zero, or positive to indicate relative order – typically implemented in different class – useful if original class does not build in desired comparison

class StudentNameComparer : IComparer { public int Compare(object o1, object o2) { Student s1 = o1 as Student; Student s2 = o2 as Student; return s1.name.CompareTo(s2.name); } }

cast compare names

24

slide-25
SLIDE 25

Using IComparer

  • IComparer object created and passed to Sort method

– comparison object used in preference to built in comparison

ArrayList students = new ArrayList(); Student ann = new Student("Ann", 8000); Student bob = new Student("Bob", 2000); students.Add(ann); students.Add(bob); StudentNameComparer cmp = new StudentNameComparer(); students.Sort(cmp);

comparer sort

25

slide-26
SLIDE 26

Stack

  • Stack provides last-in-first-out storage

– data stored in array – array resized automatically as needed

using System.Collections; class Trace { Stack callChain = new Stack(); ... }

create Stack to store sequence

  • f method calls

26

slide-27
SLIDE 27

Stack services

  • Stack offers standard last-in-first-out services

– Push – Peek – Pop

Stack s = new Stack(); s.Push("aaa"); s.Push("bbb"); string t = (string)s.Peek(); string u = (string)s.Pop(); ...

add examine remove

27

slide-28
SLIDE 28

Queue

  • Queue provides first-in-first-out storage

– data stored in array – array resized automatically as needed

using System.Collections; class Watcher { Queue events = new Queue(); ... }

create Queue to store events

28

slide-29
SLIDE 29

Queue services

  • Queue offers standard first-in-first-out services

– Enqueue – Dequeue – Peek

Queue q = new Queue(); q.Enqueue("aaa"); q.Enqueue("bbb"); q.Enqueue("ccc"); string s = (string)q.Peek(); string t = (string)q.Dequeue();

add examine remove

29

slide-30
SLIDE 30

Hashtable

30

  • Hashtable provides collection of key/value pairs

– often called a map – data stored in hash table – stores object reference for both key and value – GetHashCode method of key used to determine placement – indexer provides convenient access

Hashtable ages = new Hashtable(); ages["Ann"] = 27; ages["Bob"] = 32; ages.Add("Tom", 15); ages["Ann"] = 28; int a = (int)ages["Ann"];

create add update retrieve

slide-31
SLIDE 31

Hashtable traversal

  • Can traverse Hashtable contents

– each element is DictionaryEntry struct – data exposed in Key and Value properties

Hashtable ages = new Hashtable(); ages["Ann"] = 27; ages["Bob"] = 32; ages["Tom"] = 15; foreach (DictionaryEntry entry in ages) { string name = (string)entry.Key; int age = (int) entry.Value; ... }

enumerate entries get key and value

31

slide-32
SLIDE 32

Summary

32

  • Collections provided in System.Collections namespace

– primary collections: Array ArrayList Hashtable – specialized collections: Stack Queue

  • Collections store object reference

– reference types are compatible – value types are automatically boxed

  • Traversal supported

– enumerators – foreach

  • ArrayList can be sorted

– must supply comparison method