340 likes | 439 Vues
Learn about .NET Generic Collection Classes and how they have evolved over versions. Explore how generic classes can generate multiple concrete classes, and discover the intricacies of using List<T>. Gain insights into Comparers for full functionality.
E N D
.NET Generic Collections Generics, Lists, Interfaces
.NET Collections and Generics A look back
.NET Collection Classes • C# has been through several versions since its inception • The first version had a set of Collection classes that represented various datastructures • They were collections of System.Object • Since everyclass derives from System.Object, any item could be stored in an object of one of these classes • A collection object could hold an int, a String, an Employee, a Student, and a Bulldozer object at the same time • Easy to add things, but tedious to retrieve/use them because what we retrieved was a System.Object, and not a Student, int, String, or a Bulldozer • Casting and relatedcoding techniques were necessary to use the items
.NET Generic Collection Classes • Beginning with version 2, .NET and C# have supported generic collection classes • A genericclass is not an actualclass but a blueprint or template from which many concreteclasses can be generated • It has a complete class definition except that it uses one or more placeholders (also called parameterized types) representing unspecifiedtypes • When it is time to use the genericclasstemplate to create an actualclass, realtypes are substituted for the placeholders Continued on the next slide
.NET Generic Collection Classes • One may create many actual classes from a generic class by substituting different actual data types for the placeholders • For example, if Group<type> is a genericcollectionclass with one “placeholder” type, one may create actualclasses from it by substituting actualtypes fortheplaceholder • Group <Student> • Group <Employee> • Group <String> • Group <FigNewton> • Objects of the resulting concrete classes may only hold object references of the designated types (and their subtypes, if any)
Example T is the placeholder or parameterized type The parameterized type can be used in the body like any actual type Substitution of actual type Substitution of different actual type
List<T> Generic array-like collection class
List<T> • C# has an ArrayList class, an object of which may contain references to System.Object items • C#’s generic List<T> is analogous to Java’sArrayList<T> • Similar to an array in many ways • May use subscript to access an item unlike in Java • List<T> may grow/shrink over time as the needs of the program change • When adding an item to the List<T> object, its internal array, managed by List<T> itself, will growif necessary to accommodate the new item
Count and Capacity of List<T> • The readonlyCount property of List<T> tells how many values are currently in the List<T> • The Capacity of List<T> tells how many total positions are in List<T> without it having to grow • This number includes those that are filled currently plus those where new items can be added without the List<T> having to grow • The Capacity ≥ Count always
Constructors for List<T> See “Help” in Visual Studio for details of all methods in the List<T> class
Limitations and Restrictions Comparers are required for full functionality
Limitations and Restrictions • The List <T> class uses both an equalitycomparer and an orderingcomparer • Equality comparers are used when we must determine whether a given value is in the list or whether a value in the list is equal to a specified value • Ordering comparers are used when one must sort the values in the list into a particular order • We must be able to decide whether one item is “smaller”, “equalto”, or “larger” than another item • We must decide what “smaller” and “larger” mean
Equality Comparer • Methods such as Contains, IndexOf, LastIndexOf, and Remove use an equalitycomparer for the list elements to determine whether two values of type T are “equal” • The default equality comparer for type T is determined as follows. • If type T implements the IEquatable <T> generic interface, then the equalitycomparer is the Equals(T) method of that interface • Otherwise, the defaultequalitycomparer is Object.Equals(Object)
Limitations and Restrictions • Methods such as BinarySearch and Sort use an orderingcomparer for the list elements • The defaultcomparer for type T is determined as follows • Iftype T implements the IComparable <T>genericinterface, then the defaultcomparer is the CompareTo(T) method of that interface • Otherwise, if typeT implements the nongenericIComparable interface, then the defaultcomparer is the CompareTo(Object) method of that interface • If type T implements neither interface, then there is no default comparer, and a comparer or comparisondelegate must be providedexplicitly
Other Limitations and Restrictions • The List <T>is not guaranteed to be sorted • You must sort the List <T>before performing operations (such as BinarySearch) that require the List <T>to be sorted • Elements in this collection can be accessed using an integerindex • Indexes in this collection are zero-based • List <T>accepts null (a nullreference) as a valid value for referencetypes • List <T> allows duplicateelements – that is, the same value may appear in the List<T> more than once
The IEquatable<T> Interface • Implementing the IEquatable<T> interface assures that data of type T can be compared for equality T t1, t2; if ( t1.Equals(t2) ) … • If you implement IEquatable <T>, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable<T>.Equals method • If you do override Object.Equals(Object) , your overridden implementation is also invoked in calls to the static Equals(System.Object,System.Object) method on your class • This ensures that all invocations of the Equals method return consistent results
Partial IEquatable<T> Example IEquatable<T>.Equals Compares 2 Persons Override of Object.Equals Compares Person to any object Uses IEquatable<T> version Override of Object.GetHashCode
IEquatable <User> Implementation Compare two Users Compare User to any object If Users are equal, their hash codes should be equal, too
The IComparable<T> Interface • Some methods of the List<T> class require that we be able tocompare 2 items of type T to determine their order • Examples include the following methods • Sort • BinarySearch • T must implement the IComparable<T>interface • T must implement a CompareTo<T> method to compare two items of type T • See the next slide for the rules that the CompareTo<T> method must follow
Rules for CompareTo<T> • For objects A, B, and C of type T these must be true: • A.CompareTo (A) is required to return zero(i.e., A == A) • If A.CompareTo(B) returns zero, then B.CompareTo(A) is required to return zero (i.e., if A==B, then B==A) • If A.CompareTo(B) returns zero and B.CompareTo (C) returns zero, then A.CompareTo (C) is required to return zero (if A==B and B==C, then A==C) • If A.CompareTo (B) returns a value other than zero, then B.CompareTo (A) is required to return a value of the opposite sign (A > B B < A and A < B B > A) • If A.CompareTo (B) returns a value x that is not equal to zero, and B.CompareTo (C) returns a value y of the same sign as x, then A.CompareTo (C) is required to return a value of the same sign as x and y ( A < B and B < C A < C; same for >)
Partial Example of IComparable<T> CompareTo<T> method
Example Output IEquality<T>
Example (continued) Uses IEquality<T> Output