Click here to Skip to main content
15,900,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
Posted
Updated 14-Jun-12 6:50am
v2

1 solution

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.
 
Share this answer
 
v5
Comments
Maciej Los 14-Jun-12 13:15pm    
Good work, my 5!
VJ Reddy 14-Jun-12 13:20pm    
Thank you, losmac :)
Sergey Alexandrovich Kryukov 14-Jun-12 15:22pm    
Right, well done, my 5.
--SA
VJ Reddy 14-Jun-12 19:51pm    
Thank you, SA :)
Espen Harlinn 14-Jun-12 17:08pm    
Nice answer, 5'ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900