列表如何删除项目? [英] How does List remove items?

查看:83
本文介绍了列表如何删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含对象的列表.如何删除对象? List会在整个集合中进行迭代,直到找到正确的项目,还是使用某种类型的hashMap查找来删除该项目?示例:

If I have a List which holds objects. How are objects removed? Does thw List iterate through the entire collection until it finds the correct item or does it use some type of hashMap lookup to remove the item? Example:

List<MyObj> myList = new List<MyObj>();

myList.Remove(someObj);

推荐答案

在此处进行解释 http://msdn.microsoft.com/zh-CN/library/6sh2ey19.aspx [ ^ ]表示

列表< T>的容量;是List< T>所包含元素的数量.能把持住.当将元素添加到List< T>时,通过重新分配内部数组,容量会根据需要自动增加.
如果可以估计集合的大小,则使用List< T>(Int32)构造函数并指定初始容量可以消除在将元素添加到List< T>时执行大量调整大小操作的需要.
可以通过调用TrimExcess方法或显式设置Capacity属性来减少容量.减少容量会重新分配内存并复制List< T>中的所有元素.
此构造函数是O(1)操作.


并在此处进行了说明 http://msdn.microsoft.com/en-us/library/cd666k3e#Y0 [ ^ ]表示

List.Remove方法使用默认的相等比较器EqualityComparer< T>确定相等性.T的默认值是列表中值的类型.

该方法执行线性搜索;因此,此方法是O(n)运算,其中n是Count.


从以上两个参考文献中可以看出,List<T>实现了array internally,而Remove method使用linear search删除了找到的first element.
It is explained here http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[^] that

The capacity of a List<T> is the number of elements that the List<T> can hold. As elements are added to a List<T>, the capacity is automatically increased as required by reallocating the internal array.

If the size of the collection can be estimated, using the List<T>(Int32) constructor and specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List<T>.

The capacity can be decreased by calling the TrimExcess method or by setting the Capacity property explicitly. Decreasing the capacity reallocates memory and copies all the elements in the List<T>.

This constructor is an O(1) operation.


And it is explained here http://msdn.microsoft.com/en-us/library/cd666k3e#Y0[^] that

List.Remove method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.


From the above two references it can be seen that the List<T> implements an array internally and the Remove method uses linear search to remove the first element found.


这篇关于列表如何删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆