Nội dung Array và ArrayList Queue và Stack Một số interface của System.Collections 2... Các chức năng này được thực thi thông qua các interface trong namespace System.
Trang 1Collections
Trang 2Nội dung
Array và ArrayList
Queue và Stack
Một số interface của System.Collections
2
Trang 3System.Array và System.Collections
Array trong C# được thực thi như 1 instance của lớp
System.Array và là 1 trong các loại lớp collection
Hạn chế: Có kích cỡ cố định, nên không thể thêm mục
mới vào cuối mảng
Các lớp Collection được dùng để thao tác danh sách các đối tượng (list of objects) và có thể triển khai nhiều chức năng hơn mảng thông thường
Các chức năng này được thực thi thông qua các interface trong namespace System.Collections Lớp thực thi các interface này có thể theo những cách khác với
System.Array.
Trang 4Class Array
Tất cả mảng đều kế thừa ngầm định từ lớp trừu tượng
Array (namespace System)
Property Length: specifies the number of elements in the array
Class Array provides static methods that provide
algorithms for processing arrays:
Sort
Copy
4
Trang 5Các hạn chế của mảng thông
thường
thường phải tạo 1 mảng mới, copy các phần tử cần giữ lại, cập nhật các tham chiếu đến mảng gốc sao cho nó cũng tham chiếu đến mảng mới.
chuyển tất cả các phần tử sau phần tử bị xóa lên
1 vị trí
chuyển các phần tử xuống 1 vị trí để tạo ô trống cho phần tử cần chèn khi đó phần tử cuối sẽ bị mất
Trang 6 Tất cả interface khai báo trong namespace
System.Collections đều có 1 loại generic tương đồng
trong namespace System.Collections.Generi c.
6
Trang 7Một số Collection nongeneric thông
Trang 9Một vài method thông dụng của ArrayList
Add : thêm 1 đối tượng vào cuối ArrayList
CopyTo(Array) : copy toàn bộ arrayList vào mảng 1 chiều
Equals(Object) xác định Object có bằng với đối tượng
hiện hành của ArrayList hay không
GetEnumerator () Returns an enumerator for the entire
ArrayList
IndexOf(Object) Searches for the specified Object and
returns the zero-based index of the first occurrence
within the entire ArrayList
Insert Inserts an element into the ArrayList at the
specified index
Trang 10Một vài method thông dụng của ArrayList
Remove Removes the first occurrence of a specific object from the ArrayList
RemoveAt Removes the element at the specified index of the ArrayList
Clear Removes all elements from the ArrayList
Reverse () Reverses the order of the elements in the
entire ArrayList
Sort () Sorts the elements in the entire ArrayList
10
Trang 11 Our ArrayList maintains a set of Car objects
class Car
{
// Public fields for simplicity.
public string PetName;
public int Speed;
// Constructors.
public Car(){}
public Car(string name, int currentSpeed)
{ PetName = name; Speed = currentSpeed;}
}
Trang 12static void ArrayListTest()
{
Console.WriteLine( "\n=> ArrayList Test:\n");
ArrayList carArList = new ArrayList();
carArList.AddRange(new Car[] { new Car( "Fred", 90, 10),
new Car( "Mary", 100, 50), new Car( "MB", 190, 11)});
Console.WriteLine( "Items in carArList: {0}", carArList.Count);
// Print out current values.
foreach(Car c in carArList)
Console.WriteLine( "Car pet name: {0}", c.PetName);
Console.WriteLine( "->Inserting new Car.");
carArList.Insert(2, new Car( "TheNewCar", 0, 12));
Console.WriteLine("Items in carArList: {0}", carArList.Count);
object[] arrayOfCars = carArList.ToArray();
for(int i = 0; i < arrayOfCars.Length; i++)
{ Console.WriteLine( "Car pet name: {0}",
((Car)arrayOfCars[i]).PetName); }} 12
Trang 13 Theo cơ chế first-in, first-out (FIFO)
Các method thông dụng của Queue :
back : Returns a reference to the last and most recently
added element at the back of the queue
empty :Tests if the queue is empty
front : Returns a reference to the first element at the front
of the queue
pop : Removes an element from the front of the queue
push : Adds an element to the back of the queue
size : Returns the number of elements in the queue
Trang 14 Thực thi cơ chế Last-in First out (LIFO)
Các method thông dụng của Stack:
GetEnumerator Returns an IEnumerator for the Stack
GetType Gets the Type of the current instance
Peek Returns the object at the top of the Stack without
removing it
Pop Removes and returns the object at the top of the Stack
Push Inserts an object at the top of the Stack
14
Trang 15So sánh Array và collection
Phải khai báo loại
cho các phần tử Không cần khai báo
Kích thước mảng là
cố định Có kích thước động
Có nhiều hơn 1 chiều Chỉ có 1 chiều
Trang 16Common collection interfaces
16
Trang 1818
Trang 19IEnumerator interface
IEnumerator là lớp cơ bản cho tất cả nongeneric
enumerators IEnumerator < T > là lớp tương đương cho phiên bản generic
Enumerators được dùng để đọc (nhưng không thể chỉnh sửa ) dữ liệu trong collection.
Enumerator lúc đầu được định vị ở trước phần tử đầu
tiên của collection
Trang 20IEnumerator interface
Các lớp Collection có thể tạo các bộ liệt kê
(enumerators) khác nhau để duyệt qua các phần tử của collection.
Tuy có nhiều cách thực thi enumerators này nhưng tất cả đều xuất phát từ IEnumerator interface nhờ đó có thể xử lý chúng 1 cách đa hình.
20
Trang 21 Đối tượng enumerator được dùng để duyệt qua từng
phần tử của collection
Enumerator như 1 con trỏ đến các phần tử trong danh
sách Lúc khởi đầu, con trỏ nằm trước phần tử đầu tiên.
Trang 22Interface of the System.Collections Namespace
Icollection: xác định các đặc tính của tất cả loại
Collection nongeneric
Icomparer : cho phép 2 đối tượng so sánh với nhau
Idictionary: cho phép đối tượng collection nongeneric biểu diễn nội dung của nó bằng cặp name/value
Ienumerable: trả về interface IEnumerator cho 1 đối tượng
Ienumerator: cho phép lập lại theo kiểu foreach đối
với các kiểu con
Ilist: cung cấp hành động thêm, xóa, và lấy chỉ mục các mục trong 1 danh sách các đối tượng
22
Trang 23ICollection interface
Là interface cơ bản cho các class trong
System.Collections namespace
ICollection kế thừa từ IEnumerable;
public interface ICollection : IEnumerable
{
int Count { get; }
bool IsSynchronized { get; }
object SyncRoot { get; }
void CopyTo(Array array, int index);
IEnumerator GetEnumerator();
}
Trang 24The Role of IDictionary
IDictionary biểu diễn 1 tập hợp các cặp name/value
public interface IDictionary :
ICollection, IEnumerable
{ bool IsFixedSize { get; }
bool IsReadOnly { get; }
// Type indexer
object this[object key] { get; set; }
ICollection Keys { get; }
ICollection Values { get; }
void Add(object key, object value);
Trang 25The Role of IList
Có 3 loại Ilist:
Read-only IList cannot be modified.
Fixed-size IList does not allow the addition or removal of
elements, but it allows the modification of existing elements
Variable-size IList allows the addition, removal, and
modification of elements.
Trang 26The Role of IList
public interface IList :ICollection, IEnumerable
{
bool IsFixedSize { get; }
bool IsReadOnly { get; }
object this[ int index ] { get; set; }
int Add(object value);
void Clear();
bool Contains(object value);
int IndexOf(object value);
void Insert(int index, object value);
void Remove(object value);
void RemoveAt(int index);
Trang 27The System.Collections.Generic Namespace
Contains numerous class and interface types that allow you to contain subitems in a variety of containers
Similar to System.Collections but more general
Differences:
• T keyword: used to represent types
• TKey keyword: used for keys