Basic knowledge of C # basics (+) IList interface-non-generic

Source: Internet
Author: User
Learn about the ICollection interface, iterations, and generic collections, and learn more about the IList interface below.
There are two types of IList interfaces that can be seen through MSDN:

The element is an IList interface of type object, which can put different types of object references;
ilist<t> generic interface that can only hold object references of the specified type.
In fact, IList and Ilist<t>, also known as vectors, are characterized by the ability to dynamically change the length of the set, without having to determine the initial length of the set, the collection will automatically change with the amount of data stored.
You can see the inheritance relationship between IList and Ilist<t>:




ComVisibleAttribute(true)]
public interface IList : ICollection, IEnumerable

public interface IList<T> : ICollection<T>, 
 IEnumerable<T>, IEnumerable


Now return to see the difference between IList and ilist<t>, see the following code, ArrayList is inherited IList, 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; // Must be cast once

             TestClass1 getC1List = list [0]; // No conversion required, so-called generic
         }
     }

     public class TestClass1
     {
     }


This is quite clear.
I. IList interface Overview
The ILIs interface inherits from the ICollection interface with the following attributes,
Count Property--Get the number of collection elements,
GetEnumerator Method--can iterate;
CopyTo Method- -copies the specified elements to another array; The
Clear Method--empties the entire collection.
IList new Attribute,
Indexer Property--accesses any element in the collection according to the index;
Add Method--Adds an element to the end of the collection;
Insert Method--Inserts the element at the specified position in the collection;
Remove Method--Removes the specified element ; (including RemoveAt)
contains method--to determine whether an object is in the collection;
IndexOf Method--finds the index position of the specified object in the collection.
In addition, the IList interface collection stores elements sequentially, without altering the order in which elements are stored. The
2, algorithm
Vector collection, and array, has the characteristics of the immediately accessible. That is, the required access time is exactly the same regardless of any unit of the access vector collection. In the vector class, actually still uses the ordinary array to record the collection data, the vector class uses some algorithm technique, lets the whole class external performance differs from the ordinary array the important characteristic: can change the array length dynamically. The algorithm is as follows:
in the case of the internal array is long enough, directly add and insert operations, in the case of insufficient number of internal numbers, according to the length of the internal array as the length of the new array, and then data removal (that is, the array array into the new array). Vectors allocate more redundant space when allocating element storage space, minimizing memory allocation times. In the case of data deletion, the internal array length is not changed, only the deleted data is overwritten with the data after being deleted.
However, each time the vector allocates space, it allocates some redundant space, which can cause the memory pressure, so it is necessary to avoid a large number of memory allocations in the program.
Third, implementation class
IList and ilist<t> implementation classes, respectively, are the ArrayList class and the List<t> class. The
ArrayList class is under the System.Collection namespace, and the
List<t> class is under the System.Collection.Specialized namespace.
Four, implementation code (non-generic)


/// <summary>
    /// Implement IList, non-generic
    /// </ summary>
    public class ArrayList: IList
    {
        /// <summary>
        /// iteration
        /// </ summary>
        public struct Enumertor: IEnumerator
        {
            /// <summary>
            /// iteration index
            /// </ summary>
            private int index;

            /// <summary>
            /// a reference to the vector class object to which the iterator belongs
            /// </ summary>
            private ArrayList arrayList;

            /// <summary>
            /// Constructor
            /// </ summary>
            /// <param name = "arrayList"> The collection class to which the iterator belongs </ param>
            public Enumertor (ArrayList arrayList)
            {
                this.arrayList = arrayList;

                this.index = -1;
            }

            /// <summary>
            /// Get the current object and return an object reference corresponding to the vector according to the value of index
            /// </ summary>
            public object Current
            {
                get
                {
                    return arrayList [index];
                }
            }

            /// <summary>
            /// Point the iterator to the next data position, by changing the value of index, 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 index to -1
            /// </ summary>
            public void Reset ()
            {
                this.index = -1;
            }
        }

        /// <summary>
        /// array holding the collection
        /// </ summary>
        private object [] array = new object [1];

        /// <summary>
        /// the length of the current collection
        /// </ summary>
        private int count;

        /// <summary>
        /// default constructor
        /// </ summary>
        public ArrayList ()
        {

        }

        /// <summary>
        /// The parameter constructor, which specifies the length of the internal array through parameters, reducing reallocation space
        /// </ summary>
        /// <param name = "capacity"> </ param>
        public ArrayList (int 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 property is read-only
            }
        }

        /// <summary>
        /// The actual length of the collection
        /// </ summary>
        public int Capacity
        {
            get
            {
                return this.array.Length;
            }
        }

        /// <summary>
        /// Is it a fixed size?
        /// </ summary>
        public bool IsFixedSize
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Whether to read-only collection
        /// </ summary>
        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// Whether it is synchronized, that is, whether it supports multi-threaded access
        /// </ summary>
        public bool IsSynchronized
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// synchronization object
        /// </ summary>
        public object SyncRoot
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// When array length is insufficient, reallocate a new array with sufficient length
        /// </ summary>
        /// <returns> </ returns>
        private object [] GetNewArray ()
        {
            return new object [(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; // Re-reference, point to the new array
            }

            // Add new elements
            this.array [this.count] = value;

            this.count = newCount;

            // Return the index position of the new element
            return this.count-1;
        }

        /// <summary>
        /// Indexer property, return an item in the vector 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 elements in the collection
        /// </ summary>
        /// <param name = "index"> </ param>
        /// <param name = "count"> </ param>
        public vo
id RemoveRange (int index, int count)
        {
            if (index <0)
            {
                throw new Exception ();
            }

            int removeIndex = index + count; // Calculate the index of the last deleted element in the set

            if (count <0 || removeIndex> this.count)
            {
                throw new Exception ();
            }

            // Delete is actually copying all elements after the element to be deleted to the position of the element to be overwritten
            Array.Copy (this.array, index + 1, this.array, index + count-1, this.count-removeIndex);

            // Reset the collection length
            this.count-= count;
        }

        /// <summary>
        /// find the corresponding array item, it is actually traversing to find
        /// </ 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 the specified element from the collection
        /// </ summary>
        /// <param name = "value"> </ param>
        public void Remove (object value)
        {
            int index = this.IndexOf (value);

            if (index> = 0)
            {
                this.RemoveRange (index, 1);
            }
        }

        /// <summary>
        /// remove the element at the specified position from the collection
        /// </ summary>
        /// <param name = "index"> </ param>
        public void RemoveAt (int index)
        {
            RemoveRange (index, 1);
        }

        /// <summary>
        /// delete the last element after getting a reference to the last element
        /// </ summary>
        /// <returns> </ returns>
        public object PopBack ()
        {
            object obj = this.array [this.count-1];

            RemoveAt (this.count-1);

            return obj;
        }

        /// <summary>
        /// get 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 ();
            }
            // Insert elements when the space is insufficient, declare a new 2x length array and copy the old data.
            // The principle of inserting data is to move all the data after the specified position back, and then place the new data in 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>
        /// See if the current collection contains the specified object
        /// </ summary>
        /// <param name = "value"> </ param>
        /// <returns> </ returns>
        public bool Contains (object value)
        {
            return this.IndexOf (value)> = 0;
        }

        /// <summary>
        /// change the length of the collection to the actual length
        /// </ summary>
        public void TrimToSize ()
        {
            // In order to eliminate the added redundancy when Add and Insert, the principle is to newly generate an array of the same length as the actual one, and then move all the values over.
            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>
        /// empty collection
        /// </ summary>
        public void Clear ()
        {
            this.count = 0;
        }
        /// <summary>
        /// get the iterator of the collection
        /// </ summary>
        /// <returns> </ returns>
        public IEnumerator GetEnumerator ()
        {
            Enumertor enumerator = new Enumertor (this);

            return enumerator;
        }

        /// <summary>
        /// transfer collection 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);
        }
    }



To invoke the test:





static void Main (string [] args)
        {
            // call test

            ArrayList myArrayList = new ArrayList ();

            myArrayList.Add (40);

            myArrayList.Add (80);

            myArrayList.Add ("Hello");

            // Use a for loop to traverse
            for (int i = 0; i <myArrayList.Count; i ++)
            {
                Console.WriteLine (myArrayList [i]);
            }

            Console.WriteLine ("---------------------");

            // use iterative 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 collection contain elements of 1?" + (MyArrayList.Contains (0)? "Include": "Does not contain"));

            Console.WriteLine ("position of element 1" + myArrayList.IndexOf (1));

            Console.ReadLine ();
        } 


Results:



The above is the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • Related Article

    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.