ArrayList | List |
---|---|
ArrayList are not strongly typed | List are strongly typed |
In ArrayList it can store any type of data, we dont have to specify the type of data it is going to store. | In List we have to specify the type of data elements it is going to store. |
Namespace : System.Collections | Namespace : System.Collections.Generic |
ArrayList needs boxing and unboxing. | No need of boxing and unboxing |
Here the elements are stored as an object type. | Here the data type it is going to store is strongly typed and is given as generic parameter. |
ArrayList myArray = new ArrayList(); myArray.Add(“Dot Net”); myArray.Add(100); //no error at compile time int sum=0; |
List<string> myArray = new List<string>(); myArray.Add(“Dot Net”); myArray.Add(100); //compile time error int sum=0; |
Tips :
- Should not use ArrayList in your code if you are using .NET >=2.0 unless you are using an interface with an old API that uses it.
- List<T> is very useful in reducing runtime errors (casting). You came to know at compile time if any casting issue is there.
Let us understand diagrammatically:
In the above figure you can see that in our arraylist when we try to store different data types values, No compile time error occurs. First two elements of the ArrayList are of type Integer and the 3rd element is of type String.
While When we try to store integer value ‘100’ in our List2 which is of List
Moreover from the figure you can see that while declaring ArrayList we are not specifing which type of data it is going to store. So it clearly means that an ArrayList stores its elements as type ‘Object’ Hence everytime you store or fetch a value boxing and unboxing takes place. And in List ‘string’ is written. so only string value is stored and string is retrieved. Hence no need of boxing and unboxing.