C # basic knowledge sorting basic knowledge (16) ilist interface -- Non-generic

Source: Internet
Author: User

I have learned about the icollection interface, iteration, and generic set. Next I will take a closer look at the ilist interface.
Through msdn, we can see that the ilist interface has two types:

The ilist interface whose elements are object types can be referenced by different types of objects;
Ilist <t> generic interface, which can only store references of specified types of objects.
In fact, ilist and ilist <t> are also called vectors, which can dynamically change the length of a set without determining the initial length of the set. The set will automatically change with the number of stored data.
We can see the inheritance relationship between ilist and ilist <t>:

[ComVisibleAttribute(true)]public interface IList : ICollection, IEnumerablepublic interface IList<T> : ICollection<T>,  IEnumerable<T>, IEnumerable

Now let's look back at the differences between ilist and ilist. The following Code shows that arraylist inherits ilist and list inherits ilist. <t>:

Public class ilistclass {void test () {testclass1 C1 = NULL; arraylist arrylist = new arraylist (); arrylist. add (C1); List <testclass1> List = new list <testclass1> (); list. add (C1); // value: testclass1 getc1array = arrylist [0] As testclass1; // You must forcibly convert testclass1 getc1list = list [0] at a time; // conversion is not required, so-called generic} public class testclass1 {}

This is quite clear.
1. ilist interface Overview
The ilis interface inherits from the icollection interface and has the following features,
Count attribute -- obtains the number of elements in a set;
Getenumerator Method -- can be iterated;
Copyto Method -- copy the specified element to another array;
Clear Method -- clear the entire set.
New Features of ilist,
Indexer Attributes -- any element in the index access set;
Add Method -- add an element to the end of the Set;
Insert Method -- insert an element to the specified position of the Set;
Remove Method -- remove a specified element; (including removeat)
Contains Method -- determines whether an object is in a collection;
Indexof Method -- query the index location of a specified object in the set.
In addition, the ilist interface set stores elements in sequence without changing the order of elements.
2. Algorithms
Like arrays, vector sets feature instant access. That is, the access time required is identical regardless of any unit in the access Vector Set. In vector classes, we still use common arrays to record the set data. Vector classes use some algorithm techniques to make the entire class behave differently from common arrays: the length of the array can be dynamically changed. The specific algorithm is as follows:
When the internal array is long enough, add and insert the internal array directly. If the length of the internal array is insufficient, the length of the new array is increased by 2 times, then, move the data (that is, move the array to the new array ). When allocating element buckets, vectors allocate redundant spaces to minimize the number of memory allocations. When data is deleted, the length of the internal array is not changed, but the deleted data is overwritten with the deleted data.
However, when the vector allocates space each time, it allocates redundant space, which may cause memory pressure. Therefore, we should avoid concentrated memory allocation for a large number of times in the program.
Iii. Implementation class
The implementation classes of ilist and ilist <t> are the arraylist class and list <t> class respectively.
The arraylist class is in the system. Collection namespace;
The list <t> class is in the system. collection. Specialized namespace.
IV. Implementation Code (non-generic)
 

/// <Summary> /// implement ilist, non-generic // </Summary> public class arraylist: ilist {// <summary> /// iteration // </Summary> public struct enumertor: ienumerator {// <summary> // iterative index /// </Summary> private int index; /// <summary> /// reference of the Vector class object to which the iterator belongs /// </Summary> private arraylist; /// <summary> /// constructor /// </Summary> /// <Param name = "arraylist"> collection class to which the iterator belongs </param> Public enumertor (arraylist ar Raylist) {This. arraylist = arraylist; this. index =-1;} // <summary> // obtain the current object, returns the object reference of the Vector Based on the index value. // </Summary> Public object current {get {return arraylist [Index] ;}} /// <summary> /// point the iterator to the next Data Location and change the index value, add 1 or subtract 1 /// </Summary> /// <returns> </returns> Public bool movenext () {If (this. index <arraylist. count) {++ this. index;} return this. index <arraylist. count;} // <summary> /// The iterator returns to the starting position and sets the index to-1 // </Summary> Public void reset () {This. index =-1 ;}//< summary> // Save the array of the Set /// </Summary> private object [] array = new object [1]; /// <summary> /// length of the current set /// </Summary> private int count; /// <summary> /// default constructor /// </Summary> Public arraylist () {}/// <summary> /// parameter constructor, use the parameter to specify the length of the internal array to reduce the space for reallocation. // </Summary> // <Param name = "capacity"> </param> Public arraylist (I NT capacity) {If (capacity <0) {Throw new exception ();} If (capacity = 0) {capacity = 1;} This. array = new object [capacity]; this. count = 0;} public int count {get {return this. count; // This attribute is read-only }/// <summary> /// actual length of use of the Set /// </Summary> Public int capacity {get {return this. array. length ;}//< summary> /// whether the size is fixed /// </Summary> Public bool isfixedsize {get {return false ;}/// <Summary >/// read-only set /// </Summary> Public bool isreadonly {get {return false ;}/// <summary >/// whether to synchronize, whether multi-thread access is supported // </Summary> Public bool issynchronized {get {return false ;}} /// <summary> /// synchronization object /// </Summary> Public object syncroot {get {return NULL ;}} /// <summary> /// when the array length is insufficient, reassign a new array with sufficient length /// </Summary> /// <returns> </returns> private object [] getnewarray () {return new o Bject [(this. array. length + 1) * 2];} public int add (object Value) {int newcount = This. count + 1; if (this. array. length <newcount) // insufficient length {object [] newarray = getnewarray (); array. copy (this. array, newarray, this. count); this. array = newarray; // rereference, pointing to new array} // Add new element this. array [this. count] = value; this. count = newcount; // return the index position of the new element. return this. count-1 ;}/// <summary> // index properties, return one of the vectors by index // /</Summary> // <Param name = "Index"> </param> // <returns> </returns> Public object this [int Index] {get {if (index <0 | index> = This. count) {Throw new exception ();} return this. array [Index];} set {If (index <0 | index> = This. count) {Throw new exception ();} This. array [Index] = value ;}} /// <summary> /// Delete the element in the Set /// </Summary> /// <Param name = "Index"> </param> /// <Param name = "count "> </Param> Public void removerange (INT index, int count) {If (index <0) {Throw new exception ();} int removeindex = index + count; // calculate the index if (count <0 | removeindex> This. count) {Throw new exception () ;}// Delete is actually to copy all elements after the element is to be deleted to the location where the element to be deleted overwrites the array. copy (this. array, index + 1, this. array, index + count-1, this. count-removeindex); // reset the set length this. count-= count;} // <summary> /// Find the corresponding array, actually, it is traversing and searching /// </Summary> /// <Param name = "value"> </param> /// <returns> </returns> Public int indexof (object value) {int Index = 0; If (value = NULL) {While (index <this. count) {If (this. array [Index] = NULL) {Return Index ;}++ index ;}} else {While (index <this. count) {If (this. array [Index]. equals (value) {Return Index ;}++ index ;}} return-1 ;}/// <summary> /// delete a specified element from the set // /</Summary> // <Param name = "value"> </param> Public void remove (object Value) {int Index = This. indexof (value); If (index> = 0) {This. removerange (index, 1 );}} /// <summary> /// Delete the element at the specified position from the set /// </Summary> /// <Param name = "Index"> </param> Public void removeat (INT index) {removerange (index, 1 );} /// <summary> /// obtain the reference of the last element and delete it. /// </Summary> /// <returns> </returns> Public object popba CK () {object OBJ = This. array [this. count-1]; removeat (this. count-1); Return OBJ ;} /// <summary> /// obtain the first element reference and delete the first element /// </Summary> /// <returns> </returns> Public object propfront () {object OBJ = This. array [0]; removeat (0); Return OBJ ;} /// <summary> /// insert element /// </Summary> /// <Param name = "Index"> </param> /// <Param name = "value"> </param> Public void insert (INT index, object value) {If (Index >=this. Count) {Throw new exception () ;}// when the inserted element has insufficient space, it also declares a new 2x length array and copies the old data. // The principle of data insertion is to move all the data at the specified position backward, and then place the new data at the specified position. Int newcount = This. count + 1; if (this. array. length <newcount) {object [] newarray = getnewarray (); array. copy (this. array, newarray, index); this. array = newarray;} array. copy (this. array, index, this. array, index + 1, this. count-index); this. array [Index] = value; this. count = newcount ;} /// <summary> /// check whether the current set contains the specified object // </Summary> /// <Param name = "value"> </param> // /<returns> </returns> P Ublic bool contains (object Value) {return this. indexof (value)> = 0 ;}/// <summary> /// change the length of the set to the actual length. /// </Summary> Public void trimtosize () {// in order to eliminate the added redundancy during add and insert operations, the principle is to generate an array with the same length as the actual one, and then move all the values. If (this. array. length> This. count) {object [] newarray = NULL; If (this. count> 0) {newarray = new object [this. count]; array. copy (this. array, newarray, this. count);} else {newarray = new object [1];} This. array = newarray; }}/// <summary> // clear the set /// </Summary> Public void clear () {This. count = 0 ;} /// <summary> /// get the iterator of the set /// </Summary> /// <returns> </returns> Public ienumerator getenumerator () {enumertor enumerator = new enumertor (this); Return enumerator ;} /// <summary> /// transfer the set element /// </Summary> /// <Param name = "targetarray"> </param> /// <Param name = "Index"> </param> Public void copyto (array targetarray, int index) {array. copy (this. array, 0, targetarray, index, this. count );}}

Call test:

 

Static void main (string [] ARGs) {// call the test arraylist myarraylist = new arraylist (); myarraylist. add (40); myarraylist. add (80); myarraylist. add ("hello"); // use the for loop to traverse for (INT I = 0; I <myarraylist. count; I ++) {console. writeline (myarraylist [I]);} console. writeline ("---------------------"); // use the iteration loop foreach (Object OBJ in myarraylist) {console. writeline (OBJ);} console. writeline ("-------------------- -"); Myarraylist. insert (1, "insert"); foreach (Object OBJ in myarraylist) {console. writeline (OBJ);} console. writeline ("---------------------"); myarraylist. remove ("insert"); foreach (Object OBJ in myarraylist) {console. writeline (OBJ);} console. writeline ("---------------------"); myarraylist. removeat (1); foreach (Object OBJ in myarraylist) {console. writeline (OBJ);} console. writeline ("-------- ------------- "); Myarraylist. clear (); foreach (Object OBJ in myarraylist) {console. writeline (OBJ);} console. writeline ("---------------------"); random Rand = new random (); For (INT I = 0; I <10; I ++) {myarraylist. add (Rand. next (10);} foreach (Object OBJ in myarraylist) {console. writeline (OBJ);} console. writeline ("---------------------"); console. writeline ("does the set contain an element of 1? "+ (Myarraylist. Contains (0 )? "Include": "does not contain"); console. writeline ("Location of element 1" + myarraylist. indexof (1); console. Readline ();}

Result:

Code download: http://download.csdn.net/detail/yysyangyangyangshan/4686479

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.