Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Collections
Objectivos
2
Collection
"red"
"yellow"
3
Motivación
foreach (int i in a)
...
4
Collection classes
5
ArrayList
- valores duplicados ok
using System.Collections;
class Department
{
create ArrayList ArrayList employees = new ArrayList();
to store Employees ...
}
ArrayList
employees object array of object references
6
ArrayList services
7
ArrayList Add
element 0 a.Add("bbb");
element 1 a.Add("aaa");
element 2 a.Add("ddd");
...
8
ArrayList Count
9
ArrayList Insert
11
ArrayList Remove
12
ArrayList Contains
13
ArrayList IndexOf
14
ArrayList indexer
15
ArrayList Capacity
16
Box/unbox
int x = 7;
boxed a.Add(x);
17
Enumeration
public interface
IEnumerator {
access data object Current { get; }
traverse bool MoveNext();
void Reset();
}
18
Traversal with enumerator
19
Traversal with foreach
20
Sort
21
IComparable
22
Using IComparable
• IComparable objects have CompareTo built in
– will be called by no argument Sort method
23
IComparer
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
sort students.Sort(cmp);
25
Stack
using System.Collections;
class Trace
create Stack {
to store sequence Stack callChain = new Stack();
of method calls ...
}
26
Stack services
s.Push("aaa");
add
s.Push("bbb");
examine string t = (string)s.Peek();
27
Queue
using System.Collections;
class Watcher
{
create Queue
to store events Queue events = new Queue();
...
}
28
Queue services
q.Enqueue("aaa");
add q.Enqueue("bbb");
q.Enqueue("ccc");
examine string s = (string)q.Peek();
29
Hashtable
ages["Ann"] = 27;
add ages["Bob"] = 32;
ages.Add("Tom", 15);
30
Hashtable traversal
ages["Ann"] = 27;
ages["Bob"] = 32;
ages["Tom"] = 15;
31
Summary
32