ArrayList is the implementation of the IList, ICollection, IEnumerable, icloneable the dynamic array of several interfaces. Even. The netframwork provides some of the more durable, more popular new classes, and ArrayList is still very useful. Here are some examples of using ArrayList in C # to see their basic usage and some advanced usage.
The Add method is basically used in every program that uses ArrayList. This method appends an element object to the end of the ArrayList. In the case of memory permitting, you can continuously add elements to this collection, and the elements are stored in the form of a heap. See the following example.
The storage of elements in the ArrayList class is type object, which means that the ArrayList object can in principle accept any value in. NET, and boxing and unboxing usually occur when a value type is stored or retrieved. See the following example.
Add one ArrayList to another ArrayList
There are several different ways to add one ArrayList to another ArrayList, but the best is to use the AddRange method. Within the. NET Framework, AddRange uses the Array.copy or CopyTo method to perform better performance than some loops. The following example.
ArrayList Count property and Clear method
The ArrayList class provides a virtual property--count, and when the Count property is used, it is not actually calculated on the number of elements in the ArrayList object, but rather returns a cached field value directly, which means that the number of elements obtained by using this property is very fast. It is generally used in a program to get its Count property directly, without having to take out the value of the property to store it in another variable.
The ArrayList class's clear method is used to remove all its elements. Inside the. NET framework, it calls the Array.clear method. Sometimes, the code might look neater compared with all the elements of the original ArrayList object, creating a new ArrayList object directly.
ArrayList's sort and reserve method
You can use the Sort method to sort ArrayList or some of its elements, by default, in ascending order. As mentioned earlier, you can accept different types of values in ArrayList, but if you want to use the sort method, you must ensure that the part of the element that is sorted is the same data type. In other words, when there are different types of elements in ArrayList, you can still sort some of its elements by using the Sort method, but you must specify the scope of that part of the element.
The reserve method is used in the same way as sort to invert the order of ArrayList or part of its elements. The same sort method is handled for different types of elements in ArrayList.