Está en la página 1de 34

Colecciones en C#

Collections
Objectivos

• Explorar las collections en System.Collections namespace


– memory management
– containment testing
– sorting
– traversal

2
Collection

• Una colección almacena un grupo de objetos.


• Proporciona operaciones para manipular contenidos.
– add
– remove
– count?
– contains?
– traverse collection of strings
– sort
"blue"
"green"

"red"
"yellow"

3
Motivación

• Basic array es demasiado simple para muchas aplicaciones.


Es eficiente, fácil de usar y seguro y tamaño fijo

array size fixed int[] a = new int[10];


at creation
a[0] = 17;
a[1] = 99;
...
int x = a[1];

foreach (int i in a)
...

4
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

5
ArrayList

ArrayList proporciona almacenamiento para la secuencia de


elementos

- valores duplicados ok

- datos almacenados en la matriz

- matriz redimensionada automáticamente según sea necesario

using System.Collections;
class Department
{
create ArrayList ArrayList employees = new ArrayList();
to store Employees ...
}

ArrayList
employees object array of object references
6
ArrayList services

ArrayList es la clase primaria para soportar el concepto de lista

public class ArrayList : IList, ICloneable


{
int Add (object value) ...
add new elements
void Insert(int index, object value) ...
void Remove (object value) ...
remove void RemoveAt(int index) ...
void Clear () ...
bool Contains(object value) ...
containment testing
int IndexOf (object value) ...
read/write existing element object this[int index] { get... set.. }

control of memory int Capacity { get... set... }


in underlying array void TrimToSize() ... ...

7
ArrayList Add

Use el método Add para agregar un nuevo elemento a ArrayList


– Agreg al final

ArrayList a = new ArrayList();

element 0 a.Add("bbb");
element 1 a.Add("aaa");
element 2 a.Add("ddd");
...

8
ArrayList Count

Count propiedad registra el número de elementos en ArrayList


– Solo lectura

ArrayList a = new ArrayList();


a.Add("bbb");
a.Add("aaa");
a.Add("ddd");
Count is 3 int n = a.Count;

9
ArrayList Insert

Use Insert método para insertar un nuevo elemento en


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

insert at index 2 a.Insert(2, "ccc");


10
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");
remove element
at index 1 a.RemoveAt(1);

11
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");
remove element
a.Remove("aaa");
equal to "aaa"

12
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");
contains? if (a.Contains("aaa"))
Console.WriteLine("found");
else
Console.WriteLine("not found");

13
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");
returns 1 int i = a.IndexOf("aaa");
...

14
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();


use Add to add a.Add("bbb");
new elements a.Add("aaa");
a.Add("ddd");

change existing element a[2] = "ccc";

read existing element string s = (string)a[2];

15
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();


specify capacity of 50 ArrayList b = new ArrayList(50);

set capacity to 100 b.Capacity = 100;

get capacity int c = b.Capacity;

16
Box/unbox

• Collections store object reference


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

ArrayList a = new ArrayList();

int x = 7;

boxed a.Add(x);

unboxed int y = (int)a[0];

17
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 {
get enumerator
IEnumerator GetEnumerator();
from collection
}

public interface
IEnumerator {
access data object Current { get; }
traverse bool MoveNext();
void Reset();
}

18
Traversal with enumerator

• 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");
get enumerator IEnumerator e = a.GetEnumerator();
from collection
advance and test while (e.MoveNext())
{
access and
string t = (string)e.Current;
cast return ...
}

19
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");
handles loop foreach (string s in a)
and cast {
...
}

20
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


{
built-in
void Sort() ...
compare
separate void Sort(IComparer comparer) ...
compare void Sort(int index, int count, IComparer comparer) ...
...
}

21
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)
{
cast Student s = o as Student;

this goes first if (this.id < s.id) return -1;

if (this.id > s.id) return 1;


parameter goes first
return 0;
equal
}
...
}

22
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);
sort according students.Sort();
to CompareTo

23
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;
cast
Student s2 = o2 as Student;
compare return s1.name.CompareTo(s2.name);
names
}
}

24
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);
comparer StudentNameComparer cmp = new StudentNameComparer();

sort students.Sort(cmp);

25
Stack

• Stack provides last-in-first-out storage


– data stored in array
– array resized automatically as needed

using System.Collections;
class Trace
create Stack {
to store sequence Stack callChain = new Stack();
of method calls ...
}

26
Stack services

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


– Push
– Peek
– Pop

Stack s = new Stack();

s.Push("aaa");
add
s.Push("bbb");
examine string t = (string)s.Peek();

remove string u = (string)s.Pop();


...

27
Queue

• Queue provides first-in-first-out storage


– data stored in array
– array resized automatically as needed

using System.Collections;

class Watcher
{
create Queue
to store events Queue events = new Queue();
...
}

28
Queue services

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


– Enqueue
– Dequeue
– Peek

Queue q = new Queue();

q.Enqueue("aaa");
add q.Enqueue("bbb");
q.Enqueue("ccc");
examine string s = (string)q.Peek();

remove string t = (string)q.Dequeue();

29
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;
add ages["Bob"] = 32;
ages.Add("Tom", 15);

update ages["Ann"] = 28;


retrieve int a = (int)ages["Ann"];

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

enumerate entries foreach (DictionaryEntry entry in


ages) {
string name = (string)entry.Key;
get key and value
int age = (int) entry.Value; ...

31
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

32

También podría gustarte