Collections 24: Collections Programming C# © 2003 DevelopMentor, Inc.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Generics, Lists, Interfaces
Data Structures and Collections
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
1 Generic Collections Chapter Objectives You will be able to Use generic collection classes available in the.NET framework.
 2006 Pearson Education, Inc. All rights reserved Collections.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
C# Programming: From Problem Analysis to Program Design1 Advanced Collections C# Programming: From Problem Analysis to Program Design 3 rd Edition 8.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 11 Arrays Continued
111 © 2002, Cisco Systems, Inc. All rights reserved.
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.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Chapter 18 Java Collections Framework
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.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
C# Collections & Generics C#.NET Software Development Version 1.0.
Session 07 Module 13 - Collections. Collections / Session 7 / 2 of 32 Review  A delegate in C# is used to refer to a method in a safe manner.  To invoke.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
1 9/22/05CS360 Windows Programming Arrays, Collections, Hash Tables, Strings.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
Generics & Collection Classes Version 1.0. Topics Generic Methods and Classes Generic Collection Classes List Enumerators Queue Stack LinkedList.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
Collections Dwight Deugo Nesa Matic
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
C# Collections & Generics
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Understanding Data Types and Collections Lesson 2.
Lecture 10 Collections Richard Gesick.
Sort & Search Algorithms
Advanced .NET Programming I 2nd Lecture
Advanced Data Collections
Computing with C# and the .NET Framework
C# Programming: From Problem Analysis to Program Design
COMP 53 – Week Eleven Hashtables.
16: Equals Equals Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 19 Java Data Structures
15: Object Object Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
COP 3503 FALL 2012 Shayan Javed Lecture 8
Chapter 5: Programming with C#
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Data Structures and Database Applications Hashing and Hashtables in C#
Data Structures and Database Applications Queues in C#
structures and their relationships." - Linus Torvalds
Web Services אוספים - Collections ליווי מקצועי : ארז קלר
CS313D: Advanced Programming Language
CS1S467 GUI Programming LECTURE 11 Collections
structures and their relationships." - Linus Torvalds
Data Structures and Database Applications Hashing and Hashtables in C#
Lecture 10 List Richard Gesick.
Java Collections Framework
Lesson 6. Types Equality and Identity. Collections.
Object Oriented Programming in java
Collections Not in our text.
Cs212: Data Structures Computer Science Department Lecture 7: Queues.
Fundaments of Game Design
Basic Collections.
Defining Interfaces using C#
Advanced .NET Programming I 3rd Lecture
structures and their relationships." - Linus Torvalds
Introduction to Java Collection
Presentation transcript:

Collections 24: Collections Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Objectives Explore collections in System.Collections namespace memory management containment testing sorting traversal Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Collection A collection stores a group of objects Provides operations to manipulate contents add remove count? contains? traverse sort collection of strings "blue" "green" "red" "yellow" Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Motivation Basic array is too simple for many applications 24: Collections Motivation Basic array is too simple for many applications efficient, easy to use, and typesafe but fixed size array size fixed at creation int[] a = new int[10]; a[0] = 17; a[1] = 99; ... int x = a[1]; foreach (int i in a) Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Collection classes 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

ArrayList ArrayList provides storage for sequence of elements 24: Collections 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 ArrayList object employees array of object references Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24: Collections 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) ... object this[int index] { get... set.. } int Capacity { get... set... } void TrimToSize() ... ... } add new elements remove containment testing read/write existing element control of memory in underlying array Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

ArrayList Add Use Add method to add new element to ArrayList 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

ArrayList Count Count property records number of elements in ArrayList 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24: Collections 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 ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); a.Insert(2, "ccc"); insert at index 2 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24: Collections 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 ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); a.RemoveAt(1); remove element at index 1 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

ArrayList Remove Use Remove method to remove element from ArrayList 24: Collections ArrayList Remove 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" Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24: Collections 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? Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24: Collections 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 ArrayList a = new ArrayList(); a.Add("bbb"); a.Add("aaa"); a.Add("ddd"); int i = a.IndexOf("aaa"); ... returns 1 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

ArrayList indexer Can use indexer to get/set elements 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

24: Collections ArrayList Capacity 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 default capacity is 16 ArrayList a = new ArrayList(); ArrayList b = new ArrayList(50); b.Capacity = 100; int c = b.Capacity; specify capacity of 50 set capacity to 100 get capacity Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Enumeration Collection contents traversed using enumerator 24: Collections 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 { object Current { get; } bool MoveNext(); void Reset(); } access data traverse Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Traversal with enumerator 24: Collections Traversal with enumerator Can traverse collection contents with enumerator get IEnumerator from collection with GetEnumerator() call MoveNext() on enumerator to advance to first element use read-only Current property to access element data call MoveNext() to advance to next element 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; ... } get enumerator from collection advance and test access and cast return Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Traversal with foreach 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Sort Can sort the contents of Array and ArrayList 24: Collections Sort 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

IComparable Build in comparison code with IComparable.CompareTo 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Using IComparable IComparable objects have CompareTo built in 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

IComparer Separate comparison code with IComparer.Compare 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Using IComparer IComparer object created and passed to Sort method 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Stack Stack provides last-in-first-out storage data stored in array 24: Collections 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 of method calls Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Stack services Stack offers standard last-in-first-out services Push 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Queue Queue provides first-in-first-out storage data stored in array 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Queue services Queue offers standard first-in-first-out services 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Hashtable Hashtable provides collection of key/value pairs 24: Collections Hashtable 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 create Hashtable ages = new Hashtable(); ages["Ann"] = 27; ages["Bob"] = 32; ages.Add("Tom", 15); ages["Ann"] = 28; int a = (int)ages["Ann"]; add update retrieve Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Hashtable traversal Can traverse Hashtable contents 24: Collections 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Summary 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 Programming C# © 2003 DevelopMentor, Inc. 12/1/2003