kalai
kalai

Reputation: 93

What is difference between ArrayList and Hashtable in C#?

I want to store a collection of data in ArrayList or Hastable but data retrival should be efficient and fast. I want to know the data structure hides between ArrayList and Hastable (i.e Linked list,Double Linked list)

Upvotes: 3

Views: 21279

Answers (3)

James Michael Hare
James Michael Hare

Reputation: 38397

An ArrayList is a dynamic array that grows as new items are added that go beyond the current capacity of the list. Items in ArrayList are accessed by index, much like an array.

The Hashtable is a hashtable behind the scenes. The underlying data structure is typically an array but instead of accessing via an index, you access via a key field which maps to a location in the hashtable by calling the key object's GetHashCode() method.

In general, ArrayList and Hashtable are discouraged in .NET 2.0 and above in favor of List<T> and Dictionary<TKey, TValue> which are much better generic versions that perform better and don't have boxing costs for value types.

I've got a blog post that compares the various benefits of each of the generic containers here that may be useful:

http://geekswithblogs.net/BlackRabbitCoder/archive/2011/06/16/c.net-fundamentals-choosing-the-right-collection-class.aspx

While it talks about the generic collecitons in particular, ArrayList would have similar complexity costs to List<T> and Hashtable to Dictionary<TKey, TValue>

Upvotes: 6

A hashtable will map string values to values in your hashtable. An arraylist puts a bunch of items in numbered order.

Hastable ht = new Hastable();
ht("examplenum") = 5;
ht("examplenum2") = 7;
//Then to retrieve
int i = ht("example");  //value of 5

ArrayList al = new ArrayList();
al.Add(2);
al.Add(3);
//Then to retrieve
int j = al[0]  //value of 2

Upvotes: 2

ciberado
ciberado

Reputation: 21

As its name implies an ArrayList (or a List) is implemented with an Array... and in fact a Hashtable is also implemented with the same data structure. So both of them have a constant access cost (the best of all possible).

What you have to think about is what kind of key do you need. If your data must be accessed with an arbitrary key (for example, a string) you will not be able to use an ArrayList. Also, a Hashtable should be your preferred choice if the keys are not (more or less) correlative.

Hope it helps.

Upvotes: 0

Related Questions