Bài giảng môn Hệ thống thông tin: Collections

ppt 28 trang phuongnguyen 3520
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng môn Hệ thống thông tin: Collections", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pptbai_giang_mon_he_thong_thong_tin_collections.ppt

Nội dung text: Bài giảng môn Hệ thống thông tin: Collections

  1. Collections 1 BM HTTT - Khoa CNTT - HUI
  2. Nội dung ◼ Array và ArrayList ◼ Queue và Stack ◼ Một số interface của System.Collections 2
  3. System.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. 3
  4. Class 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
  5. Các hạn chế của mảng thông thường ◼ Khi muốn định lại kích cỡ 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. ◼ Nếu muốn xóa 1 phần tử khỏi mảng, phải chuyển tất cả các phần tử sau phần tử bị xóa lên 1 vị trí ◼ Khi muốn chèn 1 phần tử vào mảng, phải 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 5
  6. Collection Overview ◼ Tất cả các lớp collection trong .NET Framework đều thực thi từ 1 tổ hợp các collection interfaces. ◼ Các collection interface khai báo các operations sẽ được thực thi trên các loại collection khác nhau. ◼ Tất cả interface khai báo trong namespace System.Collections đều có 1 loại generic tương đồng trong namespace System.Collections.Generic. 6
  7. Một số Collection nongeneric thông dụng ◼ ArrayList ▪ Represents a dynamically size array of objects ◼ Hashtable ▪ Represents a collection of objects identified by a numerical ◼ Queue ▪ Represents a standard FIFO queue ◼ SortedList ▪ Like a dictionary ▪ The elements can be accessed by ordinal position ◼ Stack ▪ A FIFO queue providing push and pop( and peek) functionality 7
  8. Lớp ArrayList ◼ Là lớp thông dụng dùng để sắp xếp lại các phần tử bên trong 1 mảng. ◼ Thực thi giao diện IList và dùng để tạo mảng có kích cỡ động (tăng giảm tùy ý) ◼ ArrayList chấp nhận giá trị null như 1 giá trị hợp lệ và cho phép các phần tử có giá trị trùng nhau. ◼ Demo Project ArrayListTest 8
  9. Mộ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 ◼ 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. 9
  10. Mộ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
  11. Example ▪ 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;} } 11
  12. static 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
  13. Queue ◼ 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. 13
  14. Stack ◼ 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
  15. So sánh Array và collection Array Collection Phải khai báo loại Không cần khai báo cho các phần tử Kích thước mảng là Có kích thước động cố định Có nhiều hơn 1 chiều Chỉ có 1 chiều 15
  16. Common collection interfaces 16
  17. IEnumerator interface ◼ IEnumerator là lớp cơ bản cho tất cả nongeneric enumerators → IEnumerator 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. 19
  18. IEnumerator 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
  19. IEnumerable interface ◼ IEnumerable interface chứa duy nhất 1 method IEnumerator GetEnumerator(); Method này trả về đối tượng enumerator thực thi interface System.Collections.IEnumerator. ◼ Đố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. 21
  20. Interface 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 ▪ IDictionaryEnumerator ▪ 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 ▪ IHashCodeProvider ▪ 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
  21. ICollection 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(); } 23
  22. The 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); void Clear(); bool Contains(object key); IDictionaryEnumerator GetEnumerator(); void Remove(object key); } 24
  23. The 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. 25
  24. The 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); } 26
  25. The 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 • TValue: used for values 27
  26. System.Collections System.Collections.generic ICollection ICollection IDictionary. IDictionary . IList IList Queue Queue Stack Stack 28