ArrayList
(1)一種非泛型的list
ArrayList is a non-generic list that accepts any Object type for its elements.
(2)其長度可根據(jù)添加的數(shù)量變動
Using the default constructor creates an empty list. As soon as elements are added to the list, the capacity of the list is extended to allow 4 elements. If the fifth element is added, the list is resized to allow 8 elements. If 8 elements are not enough, the list is resized again to contain 16 elements. With every resize the capacity of the list is doubled.
(3)長度改變的原理
When the capacity of the list changes, the complete collection is reallocated to a new memory block. With the implementation of List<T>, an array of type T is used. With reallocation, a new array is created, and Array.Copy copies the elements from the old array to the new array. To save time, if you know the number of elements in advance, that should be in the list; you can define the capacity with the constructor.
當(dāng)長度改變時雳刺,重新分配一塊內(nèi)存闻蛀,創(chuàng)建一個新的array见咒,舊的array被copy
(4)兩個屬性:Capacity和Count
1)Capacity:容量
You can get and set the capacity of a collection by using the Capacity property.
eg:
List<int> intList = new List<int>(10);
intList.Capacity = 20;
2)Count:元素個數(shù)
The number of elements in the collection can be read with the Count property.
eg:
intList.Count
(5)TrimExcess:可以去掉一些用不到的
If you are finished adding elements to the list and don’t want to add any more, you can get rid of the unneeded capacity by invoking the TrimExcess method; however, because the relocation takes time, TrimExcess has no effect if the item count is more than 90 percent of capacity.
eg:
intList.TrimExcess();