We use List whenever we need a list. I notice now that there is a LinkedList.
I was wondering what was the difference between these 2, and when you should use one over the other.
Linked lists are an ordered collection of objects. So what makes them different from normal lists? Linked lists differ from lists in the way that they store elements in memory. While lists use a contiguous memory block to store references to their data, linked lists store references as part of their own elements.
Remove(T): This method is used to remove the first occurrence of the specified value from the LinkedList. RemoveFirst(): This method is used to remove the node at the start of the LinkedList. RemoveLast(): This method is used to remove the node at the end of the LinkedList.
lists are stored sequentially in memory. the elements are stored one after the other. they are faster to access, but slower in addition or deletion of elements. linked lists are not stored sequentially in memory.
In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list.
Well, List<T>
is basically backed by an array which is usually bigger than the current number of items. The elements are put in an array, and a new array is created when the old one runs out of space. This is fast for access by index, but slow at removing or inserting elements within the list or at the start. Adding/removing entries at the end of the list is reasonably cheap.
LinkedList<T>
is a doubly-linked list - each node knows its previous entry and its next one. This is fast for inserting after/before a particular node (or the head/tail), but slow at access by index.
LinkedList<T>
will usually take more memory than List<T>
because it needs space for all those next/previous references - and the data will probably have less locality of reference, as each node is a separate object. On the other hand, a List<T>
can have a backing array which is much larger than its current needs.
A List<T>
is actually an array, meaning that its Add
operation is O(1) at the end and O(n) at the front, but you can index into it in O(1). A LinkedList<T>
is, as it says, a linked list. Since it's doubly-linked, you can add items to the front or back in O(1) but indexing into it is O(n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With