Collection

ArrayList

(1)一种非泛型的list
ArrayList is a non-generic list that accepts any Object type for its elements.
(2)其长度可根据添加的数量变动
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.
当长度改变时,重新分配一块内存,创建一个新的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:元素个数
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();

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。