In C#, the ArrayList class is part of the .NET Framework and provides a dynamic array that can store objects of any type. The ArrayList class has several constructors that can be overloaded to initialize an ArrayList instance in different ways. Here are the overloaded constructors for the ArrayList class:
1. Default Constructor:
public ArrayList();
2. Constructor with Capacity: public ArrayList(int capacity);
This constructor creates an ArrayList with the specified initial capacity.Example:
using System;
using System.Collections;
class Program
{
static void Main()
{
// Initialize an ArrayList with a specified initial capacity of 5
ArrayList arrayList = new ArrayList(5);
// Add elements to the ArrayList
arrayList.Add("Apple");
arrayList.Add("Banana");
arrayList.Add("Cherry");
// Display the elements of the ArrayList
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
}
}
3. Constructor with ICollection:
public ArrayList(ICollection c);
This constructor creates an ArrayList that contains elements copied from the specified collection.
Example:
using System;
using System.Collections;
class Program
{
static void Main()
{
// Create an ICollection (for example, an array)
int[] numbers = { 1, 2, 3, 4, 5 }; // Array is an ICollection
// Initialize an ArrayList using the ICollection
ArrayList arrayList = new ArrayList(numbers);
// Display the elements of the ArrayList
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
}
}
What is the capacity of an ArrayList object when it is created in C#?
In C#, when you create an ArrayList object, it initially has a default capacity of 4 elements. This means that the ArrayList can hold up to 4 elements without resizing its internal storage.
However, the ArrayList class automatically increases its capacity as needed to accommodate more elements. When the number of elements in the ArrayList exceeds its current capacity, the ArrayList automatically reallocates its internal storage to accommodate more elements, usually by doubling its capacity.
It's important to note that starting with .NET Framework 2.0, the List<T> class is generally preferred over ArrayList due to its type safety, better performance, and improved features. The List<T> class is part of the System.Collections.Generic namespace and is strongly typed, allowing you to work with a specific type of elements, unlike ArrayList, which stores elements as objects and requires boxing and unboxing.
No comments:
Post a Comment