Thursday, October 2, 2008

What is the difference between Array List and Hash Table?

Array list and hash table are the collection objects whose basic necessacity is to collect or hold a group of objects need not be of same type.

They are similar to what we say arrays in C- Programming or java or any programming languages.
Arrays are only capable of storing specific types which are predefined on declaration. Where as Array list or hash table shall store objects of any type and need not be predefined.

Arrays declaration should include its maximum size capability at the time of declaration, where array list or hash table shall increase there size dynamically based upon the objects added or collected using IList interface.

(Please refer my earlier post regarding value and reference type Refernce type and value type).

Arrays are similar to value types where as Array lists and Hash table are reference types that is different reference variables for Array list or Hash table (object) can be used in entire application to access same array list or Hash table object. Where as for Arrays you can have only one value type variable to access specific array location.

So at last I mean to say that the above are few of the reasons why Array lists and Hash tables are driven into enough existence.

Then what is the reason behind creating both Array list and Hash table.

The main difference is Array list implements IList interface where as Hash table implements IDictionary interface.

The interface names it self explains why there are Array list and Hash table collections.
Example : -

List out all the names in a class whose age is above 20.

In this case I use array list.

List out all the names in a class whose age is above 20 and also should be identified with there Roll Numbers.

In this case I use Hash table.

So hash table is similar to a dictionary to retrieve a value (Student names) based upon a unique key (Roll No). Array list is blindly adding items or values (Student names) but not required to bother to identify.
Also Values added to a hash table can be duplicates but key should not be.
In the above example you cannot a student more than once with his roll number, which will throw an exception saying key value pair already exists.

The values we add to a array list or hash table, similarly key to hash table can be any type (object of user defined or frame work defined object or primitive data type).

Syntax :-

Array List

ArrayList objList=new ArrayList();
“Srinivas”,”Bharani” ->Items or Values.

Hash Table

HashTable objHashTable=new HashTable();
1,2-> Keys
“Srinivas”,”Bharani” -> Values.

No comments:

Post a Comment