Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between LinkedList and ArrayList, and when to use which one?

Tags:

c#

What is the difference between LinkedList and ArrayList? How do I know when to use which one?

like image 314
Amit Avatar asked Apr 20 '10 16:04

Amit


2 Answers

The main difference between ArrayList and List<T>, LinkedList<T>, and other similar Generics is that ArrayList holds Objects, while the others hold a type that you specify (ie. List<Point> holds only Points).

Because of this, you need to cast any object you take out of an ArrayList to its actual type. This can take a lot of screen space if you have long class names.

In general it's much better to use List<T> and other typed Generics unless you really need to have a list with multiple different types of objects in it.

like image 99
Cypher2100 Avatar answered Sep 26 '22 06:09

Cypher2100


ArrayList has a good replacement which is List<T>.

In general, List<T> is a wrapper for array - it allows indexing and accessing items in O(1), but, every time you exceed the capacity an O(n) must be paid.

LinkedList<T> won't let you access items using index but you can count that insert will always cost O(1). In addition, you can insert items in to the beginning of the list and between existing items in O(1).

I think that in most cases List<T> is the default choice. Many of the common scenarios don't require special order and have no strict complexity constraints, therefore List<T> is preferred due to its usage simplicity.

like image 34
Elisha Avatar answered Sep 25 '22 06:09

Elisha