Capacity property of ArrayList

In this article I will explain the capacity property of ArrayList.
  • 4031

Introduction

Capacity property of ArrayList Gets or sets the number of elements that the ArrayList can contain. The default capacity of an ArrayList is 4. If I add 5th elements then its capacity becomes doubled (that is 8) relative to the previous one (that is, 4),similarly if their are eight element in the arraylist and I add 9th element then the capacity become double of 8,so that now the capacity will be 16,if their are more than 8 element in the arraylist and so on.

Example

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            ArrayList arr = new ArrayList();

            arr.Add("One");

            arr.Add("Two");

            Console.WriteLine("Elements of ArrayList");

            Console.WriteLine();

            foreach (object obj in arr)

            {

                Console.WriteLine(obj);

            }

            Console.WriteLine();

            Console.WriteLine("Capacity of the ArrayList is:" + arr.Capacity);

            Console.WriteLine();

            Console.WriteLine("//Adding Three more elements");

            Console.WriteLine("Elements of ArrayList");

            Console.WriteLine();

            arr.Add("Three");

            arr.Add("Four");

            arr.Add("Five");

            foreach (object obj in arr)

            {

                Console.WriteLine(obj);

            }

            Console.WriteLine();

            Console.WriteLine("Now the Capacity is:" + arr.Capacity);

            Console.WriteLine();

            Console.WriteLine("//Adding Four more elements");

            Console.WriteLine("Elements of ArrayList");

            arr.Add("Six");

            arr.Add("Seven");

            arr.Add("Eight");

            arr.Add("Nine");

            foreach (object obj in arr)

            {

                Console.WriteLine(obj);

            }

            Console.WriteLine();

            Console.WriteLine("Now the Capacity is:" + arr.Capacity);

        }

    }

}

 

Output

capacity.jpg 

 

Further Readings
 
You may also want to read these related articles.

Ask Your Question  

Got a programming related question? You may want to post your question here

 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.