Creating an ArrayList having specified initial capacity in C#

CsharpServer Side ProgrammingProgramming

To create an ArrayList having specified initial capacity, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      ArrayList list1 = new ArrayList(5);
      list1.Add("A");
      list1.Add("B");
      list1.Add("C");
      list1.Add("D");
      Console.WriteLine("Capacity in ArrayList1 = "+list1.Capacity);
      Console.WriteLine("Elements in ArrayList1...");
      foreach (string res in list1) {
         Console.WriteLine(res);
      }
      ArrayList list2 = new ArrayList(10);
      list2.Add("A");
      list2.Add("B");
      list2.Add("C");
      list2.Add("D");
      list2.Add("E");
      list2.Add("F");
      list2.Add("G");
      list2.Add("H");
      list2.Add("I");
      Console.WriteLine("Capacity in ArrayList2 = "+list2.Capacity);
      Console.WriteLine("Elements in ArrayList2...");
      foreach (string res in list2) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Is ArrayList1 equal to ArrayList2? = "+list1.Equals(list2));
      list2.RemoveRange(3, 2);
      Console.WriteLine("Elements in ArrayList2 after removing elements in a range...");
      foreach (string res in list2) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Capacity in ArrayList2 = "+list2.Capacity);
   }
}

Output

This will produce the following output −

Capacity in ArrayList1 = 5
Elements in ArrayList1...
A
B
C
D
Capacity in ArrayList2 = 10
Elements in ArrayList2...
A
B
C
D
E
F
G
H
I
Is ArrayList1 equal to ArrayList2? = False
Elements in ArrayList2 after removing elements in a range...
A
B
C
F
G
H
I
Capacity in ArrayList2 = 10

Example

Let us see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      ArrayList list = new ArrayList(5);
      list.Add("A");
      list.Add("B");
      list.Add("C");
      list.Add("D");
      Console.WriteLine("Capacity in ArrayList = "+list.Capacity);
      Console.WriteLine("Count of elements in ArrayList = "+list.Count);
      Console.WriteLine("Elements in ArrayList...");
      foreach (string res in list) {
         Console.WriteLine(res);
      }
      list.Clear();
      Console.WriteLine("Capacity in ArrayList = "+list.Capacity);
      Console.WriteLine("Count of elements in ArrayList = "+list.Count);
   }
}

Output

This will produce the following output −

Capacity in ArrayList = 5
Count of elements in ArrayList = 4
Elements in ArrayList...
A
B
C
D
Capacity in ArrayList = 5
Count of elements in ArrayList = 0
raja
Published on 06-Dec-2019 11:34:35
Advertisements