Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between List<T> and LinkedList<T>

Tags:

c#

c#-4.0

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.

like image 404
Shiraz Bhaiji Avatar asked Nov 25 '10 16:11

Shiraz Bhaiji


People also ask

What is the difference between a list and a LinkedList?

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.

What is T linked list?

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.

What's the difference between list and linked list Java?

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.

Which is better list or linked list?

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.


2 Answers

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.

like image 192
Jon Skeet Avatar answered Oct 02 '22 19:10

Jon Skeet


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).

like image 22
Gabe Avatar answered Oct 02 '22 20:10

Gabe