What is Arraylist?

What is  Arraylist ?

ArrayList is a non-generic collection of objects whose size increases dynamically.

It is the same as Array except that its size increases dynamically.

An ArrayList can store elements of any data type, including integers, strings, objects, etc.

It’s part of the "System.Collections" namespace .


Example

Create an ArrayList


using System.Collections;

ArrayList arlist = new ArrayList(); 

// or 

var arlist = new ArrayList(); // recommended 



Adding Elements in ArrayList

Use the Add () method To add an element in the arraylist

An ArrayList can contain multiple null and duplicate values.


Example

var arlist1 = new ArrayList();

arlist1.Add(1);

arlist1.Add("Bill");

arlist1.Add(" ");

arlist1.Add(true);

arlist1.Add(4.5);

arlist1.Add(null);


Adding elements using object initializer syntax

var arlist2 = new ArrayList()

                {

                    2, "Steve", " ", true, 4.5, null

                };



Accessing an ArrayList

The ArrayList class implements the IList interface. So, elements can be accessed using indexer, in the same way as an array. Index starts from zero(0) and increases by one for each subsequent element


Iterate an ArrayList

use the foreach and the for loop to iterate an ArrayList. The Count property of an ArrayList returns the total number of elements in an ArrayList


Remove Elements from ArrayList

Use the Remove(), RemoveAt(), or RemoveRange methods to remove elements from an ArrayList.


Example

arList.Remove(null); //Removes first occurrence of null

arList.RemoveAt(4); //Removes element at index 4

arList.RemoveRange(0, 2);//Removes two elements starting from 1st item (0 index)


Check Element in ArrayList

Use the Contains() method to determine whether the specified element exists in the ArrayList or not. 


Get count of element in Arraylist

Gets the number of elements using count() method in the ArrayList

Post a Comment (0)
Previous Post Next Post